0

How can I rearrange the code below to output 0011223344 instead of 01234<random values>? I'm relatively new to promises and don't know how to batch the promises in a way that the second one only executes when the first one is resolved.

function getPromise(value) {
  return new Promise(function(resolve, reject) {
    console.log(value);
    setTimeout(function () {
      resolve(value);
    }, Math.random() * 1000);
  });
}

for (var i = 0; i < 5; i++) {
  getPromise(i).then(console.log);
}

EDIT

In the real scenario the number of promises is random and unpredictable. Since promises inner code start to being executed immediately after creation, I can't have something like a promises array to iterate over, for example.

I guess that's the reason because I couldn't make it work with Promise.all.

  • if this is used in NodeJS, you could use a library like `async` that has a `async.series()` and `async.waterfall()` methods. Maybe it can also be used client-side. – Jeremy Thille Aug 24 '17 at 15:07
  • 2
    Possible duplicate of [Is Node.js native Promise.all processing in parallel or sequentially?](https://stackoverflow.com/questions/30823653/is-node-js-native-promise-all-processing-in-parallel-or-sequentially) – zero298 Aug 24 '17 at 15:07
  • `[0,1,2,3,4].reduce((acc, i) => { return acc.then(() => { return getPromise(i).then(console.log) }); }, Promise.resolve());` which (slowly) outputs 0011223344 to the console. – Jared Smith Aug 24 '17 at 15:10
  • @zero298 See my edit, please. – LF Bittencourt Aug 24 '17 at 16:22
  • @JaredSmith Your solution works too. Thanks! – LF Bittencourt Aug 24 '17 at 16:26
  • Give a more concrete example of a scenario where you would not know the number of things to execute before kicking off the first promise. I don't understand how you expect to wait for all of your non-quantifiable tasks to finish if you don't have a way to quantify "all of them". – zero298 Aug 24 '17 at 16:27
  • @JeremyThille - combining Promises (which is what the question is about) with assyncjs is a recipe for disaster – Jaromanda X Aug 24 '17 at 22:00
  • No, I wouldn't combine promises and Async. One either uses promises _or_ Async. – Jeremy Thille Aug 25 '17 at 07:09

1 Answers1

3

Await the previous one, then execute the next:

 var promise = Promise.resolve();
 for (let i = 0; i < 5; i++) {
  promise = promise.then( _=> getPromise(i).then(console.log) );
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151