0

Is there a way to create a JavaScript function that:

  1. Takes a function as an argument which returns a promise
  2. Returns after the previous call's returned

For example:

function resolveInOrder(fun: ()=>Promise<any>): Promise<void> {
   return fun().then(result => console.log(result));
}

resolveInOrder(()=>somePromise1);
resolveInOrder(()=>somePromise2);
resolveInOrder(()=>somePromise3);

Should result in (independently of how long it takes to resolve each promise):

somePromise1Result
somePromise2Result
somePromise3Result
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49
  • Assuming we whip up a solution where we store the promises inside an array and wait until `Promise.all` resolves. What happens when you are trying to add 5 promises to the queue and you have done so uptil 3 and then all promises already in queue resolve before you get to the last one? Don't you need a trigger then? To start executing the promises in queue when you tell it to start? – rahulpsd18 Jan 19 '21 at 22:22
  • 1
    You can chain these like `somePromise1.then(() => somePromise2).then(() => somePromise3)`, etc. Is there a reason that won't work? – Explosion Pills Jan 19 '21 at 22:22
  • @ExplosionPills These promises can't be chained like that because resolveInOrder() is called from external services multiple (unknown how many) times – Janek Czarnota Jan 20 '21 at 07:37
  • @JanekCzarnota in that case, I think that you will have to call it recursively – Explosion Pills Jan 20 '21 at 17:52

0 Answers0