1

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.

PaolaJ.
  • 10,872
  • 22
  • 73
  • 111

1 Answers1

1

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
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks, do you have idea how to deal with array of promises when number is not known – PaolaJ. Jan 27 '14 at 22:44
  • @PaolaJ.: Sure: `deferred.apply(undefined, theArray)(function(result) { ... });` More: [`Function#apply`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.3). At one point I was going to edit that in, clearly I should have. :-) *Edit:* And now I have. – T.J. Crowder Jan 27 '14 at 22:46