How do I chain a set of functions together using promises and q in node.js?

I have some dynamic data that needs to have work performed on it. The work must happen sequentially. Using the Q Library, I'd like to create an array of functions and execute the code sequentially using sequences. I can't seem to quite figure out the syntax to achieve this.

const fruits = ["apple", "cherry", "blueberry"]

function makeFruitPie (fruit) {
  return Q.Promise((resolve, reject) => {
    // Do some stuff here
    resolve(fruit+" pie")

    // Error handling here
    reject(new Error(""))
  })
}

const fruitFuncs = new Array(fruits.length)

for(var i = 0; i < fruits.length; i++) {
  fruitFuncs[i] = makeFruitPie(fruits[i])
}

// Stole this example from the github docs but can't quite get it right.
i = 0
var result = Q(fruits[i++])
fruitFuncs.forEach((f) => {
  result = result(fruits[i++]).then(f)
})

With these lines

for(var i = 0; i < fruits.length; i++) {
  fruitFuncs[i] = makeFruitPie(fruits[i])
}

you already run the functions and, hence, their processing will begin.

Assuming you want the execution of the functions in sequence, the following would be more appropriate:

// construct the pipeline
const start = Q.defer();
let result = start.promise; // we need something to set the pipeline off
fruits.forEach( (fruit) => {
  result = result.then( () => makeFruitPie( fruit ) );
});

// start the pipeline
start.resolve();


Sidenote: There is a native Promise implementation supported by almost all environments. Maybe consider switching from the library backed version.

Promise Chains with Node.js (Example), What happens if we want to set off an asynchronous function and wait until we get a result before executing the behavior of the next promise? Q� If you want to chain those functions with promises, then they have to return promises. If you want to chain them with async module, then they have to take callbacks as arguments. Right now they neither return a promise (or anything else), nor do they take callbacks (or anything else) as arguments. If the function doesn't take a callback and doesn't return anything then all you can do is call it and that's it.

You can use Promise.all

Promise.all(fruits.map(fruit=>makeFruitPie(fruit).then(res=> res) )).
then(final_res => console.log(final_res))

final_res will give you array of results

Using Promises, Modern functions return a promise that you can attach your callbacks to instead: One of the great things about using promises is chaining. One case of special usefulness: when writing code for Node.js, it's common that modules you include in The first mistake is to not chain things together properly. Promises can also be chained together to use the state of settled promises (resolved or rejected) and the promises’ values to control the flow of execution in your program. This is useful when you have a sequence of asynchronous operations to perform that each depend on the results of the previous operation: the next step in the chain isn’t

you could use for..of and do things sequentially. something like this

const Q = require("q");

const fruits = ["apple", "cherry", "blueberry"];

function makeFruitPie(fruit) {
  return Q.Promise((resolve, reject) => {
    // Do some stuff here
    resolve(`${fruit} pie`);

    // Error handling here
    reject(new Error(""));
  });
}

for (const fruit of fruits) {
  const result = await makeFruitPie(fruit);
  console.log(result);
}

By the way also worth considering native Promise insteead of using q

Promises in Node.js: An alternative to callbacks – Build Smart. Build , Learn why and how to use promises in Node.js It's helpful to think of then not as a function that takes two callbacks ( onFulfilled and Since then returns a promise, it means promises can chain together to avoid the deep� For example, you need to do the following: read a MongoDB collection, call an external API, call some other API, save some data in MongoDB. In each step you need the result of the previous step. Using callbacks can make your code very messy. This is an example when using JavaScript promises and chaining them together would make things easier

How to Compose Node.js Promises with Q, How to Compose Node.js Promises with Q We learned the benefits of using promises over raw callbacks. The value returned from a chain of promises is itself a promise. function forever (fn) { return fn().then(function () { return forever( fn) // re-execute if successful }) } // console.error only ever called if� If you have a number of things you'd like to do in a specific order, you can set up a promise chain by using something like: first_promise() .then(function() { return second_promise(); }) .then(function() { return third_promise(); })

Node.js Promise Tutorial, But sometimes callback functions can become a nightmare when they start instance where you would need to nest multiple callback functions together. In order to use promises in a Node.js application, the 'promise' module updates an Employeename in the 'Employee' collection by using promises. Using callback functions in Node.js does have its disadvantages. Sometimes during the process of development, the nested use of callback functions can make the code messier and difficult to maintain. Most of the issues with nested callback functions can be mitigated with the use of promises and generators in node.js

bellbind/using-promise-q: [JavaScript][promise][tutorial , GitHub is home to over 50 million developers working together to host and review code, In node.js or JS on HTML, using asynchronous actions is usually coded as the using-promise.js var httpGet = function (opts) { var deferred = Q.defer(); chain-nested-callback.js http.get(url.parse("http://example.org"), function (res)� Now let's look at an example of how we can use "promises" from within a Node.js application. In order to use promises in a Node.js application, the 'promise' module must first be downloaded and installed. We will then modify our code as shown below, which updates an Employeename in the 'Employee' collection by using promises.

Comments
  • Thanks for the answer. This is the one that most correctly answers the OP, I see the logic here but I think something is off syntactically. I'm getting 'result.then' is not a function. Back on the node game after years out (last time we liked async) so I'm just having trouble getting in the promise mindset. Once again, thanks for the help.
  • @SemperFly You're right. I'm just more used to the native implementation nowadays. I corrected the above code (result = start-> result = start.promise). Please check, if that works.
  • That was it. Thanks.
  • Follow-up on this, what's the best way to set a 'finally' on this set of Promises?
  • @SemperFly If you want a "real" finally result.catch( (e) => console.error( e ) ).then( () => /* do something */ ). If you just want to do something after the pipeline has successfully executed, you can leave out the .catch()