-1

I am working on old project that doesn't supports ES6 standards.

For ease of understanding i will write the code i am trying to reach, Please translate the following code without using async/await pair.

async function doSomeCalls(arrayWithNeededCalls){
    for(let i = 0; i < arrayWithNeededCalls.length; i++){
      await makeSomeCall(arrayWithNeededCalls[i]);
      console.log("Call: ", i, " Completed going to next one");
    }
}

I tried to use

  Promise.all()

But it doesn't wait one promise to be completed before running second one.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Levan Lomia
  • 88
  • 1
  • 8
  • 1
    Hi, could you add what you've tried so far ? This is not a coding service, try to solve your problem and if you are having issues, we can help you. – Nicolas Oct 01 '19 at 17:56
  • 1
    arrayWithNeededCalls map to Promises and use `Promise.all` for parallel or reduce arrayWithNeededCalls to one promise – HMR Oct 01 '19 at 17:56
  • Hello @Nicolas this code is pretty much everything i am trying to achieve but in older ways for legacy project. – Levan Lomia Oct 01 '19 at 18:02
  • Aren't there tools out there that can translate newer features to older standards? Babel or something? – melpomene Oct 01 '19 at 18:04

2 Answers2

2

You want to wait for your promises one by one, in order, so you should use recursion:

const doSomeCalls = (arrayWithNeededCalls) => {
  const processCall = (index) => makeSomeCall(arrayWithNeededCalls[index]).then(res => {
    console.log(`Call ${index} Completed going to next one`);
    if (index < arrayWithNeededCalls.length) {
      return processCall(index+1);
    }
  });
  return processCall(0);
}
ChrisG
  • 2,637
  • 18
  • 20
0

UPDATE: HRM comment looks much better:

Since OP is ignoring the value(s) returned by the promises you can do:

arrayWithNeededCalls.reduce( (result, item) => result.then(() => makeSomeCall(item)), Promise.resolve() );

OLD: In case if you need to run them one by one:

makeSomeCall(arrayWithNeededCalls[0])
    .then(() => makeSomeCall(arrayWithNeededCalls[1]))
    .then(() => makeSomeCall(arrayWithNeededCalls[2]))
    .then(() => makeSomeCall(arrayWithNeededCalls[3]))

But if you don't know exact promises but use just array of them - await is the best solution

Alex Vovchuk
  • 2,828
  • 4
  • 19
  • 40