0

How to solve this async problem ? (using node.js)

A promise is iterating through a list, and multiple async functions are called with each iteration. How do I know when all async functions are finished, so that I can resolve the promise ?

All I found yet is to use a setTimeout() which isn't efficient at all.

Here is a simplified sample of my code :

function myFunction(parameter){
    return new Promise(function (resolve, reject) {
        var resultToReturn = []
        _.each(list, function(el){
            doSomethingAsync(el, function(result){
                resultToReturn.push(result)
            });
            doSomethingElseAsync(el, function(result){
                resultToReturn.push(result)
            });
        });
        // How to call this ⬋ only when all async functions are finished ?
        resolve(resultToReturn)
    });
}

myFunction(IAmAParameter).then(function(resultFromPromise){
    console.log(resultFromPromise);
});

I know this kind of question was already asked many times, but answers were too specific and not relevant in this case.

Ex. :

Community
  • 1
  • 1
  • With promises you can use `Promise.all(promises).then(doSomething)` – elclanrs Feb 25 '16 at 21:53
  • There is a `.catch` with `Promise.all()`, and it can be a gotcha... – dandavis Feb 25 '16 at 21:58
  • @dandavis: You mean you'd prefer [this](http://stackoverflow.com/q/31424561/1048572)? – Bergi Feb 25 '16 at 22:04
  • @Bergi: perhaps something like that if needed, just raising awareness... – dandavis Feb 25 '16 at 22:13
  • I think you need a combination of `Promise.map` and `Promise.all` function myFunction(parameter){ return Promise.map(list, function(el) { return Promise.all([ doSomethingAsync(el, function(result){ return result; }), doSomethingElseAsync(el, function(result){ return result; }) ]) }) } You will also need to use `bluebird` for the `Promise.map` – tubu13 Feb 25 '16 at 22:23
  • Using multiple `Promise.all` solved my issue. Thanks ! –  Feb 26 '16 at 16:36

0 Answers0