How to async way call 10 functions and collect all results and know when all are finished?

StackOverflow https://stackoverflow.com/questions/21392901

  •  03-10-2022
  •  | 
  •  

سؤال

I am using deferred module for Node.js and I have created deferred functions which fetch data from distant server. I need to fetch 10 files from different distant server, how to do this with promise to know when all are finished and fetch all then results in array ? At the moment I have closure and I am fetching next file only when I have done with previous but it is sync and slow.

هل كانت مفيدة؟

المحلول

According to the documentation of what I assume is the module you're using, you can do this:

deferred(delayedAdd(2, 3), delayedAdd(3, 5), delayedAdd(1, 7))(function (result) {`
    console.log(result); // [5, 8, 8]`
});

E.g.:

deferred(promise1, promise2, promise3)(function (result) {
    // `result` is an array of the results
});

On the link above, search for "Grouping Promises" (although it doesn't have much more than the above).

If you have an array of promises, you can use Function#apply to do the above:

deferred.apply(undefined, theArray)(function (result) {
    // `result` is an array of the results
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top