0

I have an async function (a Promise) which does some things. I have to call it N times. Every call represents a simulation point. My first guess was to use a loop:

for(let i=0; i < N; i++) {
    myAsyncFunc(data[i])
     .then(() => myAsyncFunc(data[i]) )
}

Obviously, this does not work because the loops and before any subsequent call to myAsyncFun. How can I call step-by-step the async function, waiting for results and proceed to the next step?

I tried whit this:

function myAsyncFunc(data) {
    return new Promise( (resolve, reject) => {
     anotherAsync.then(resolve).catch(reject);
    }
}
function simulate(mode) {

    [...Array(10)].reduce((p, _, i) =>
        p.then(_ => new Promise(resolve => {
            myAsyncFunc(data[i]); // <== this return a Promise
        }
        ))
        , Promise.resolve());
}

But the functions myAsyncFunc are not called in sequence.

gdm
  • 7,647
  • 3
  • 41
  • 71
  • Are you opposed to `async/await` ? – Cody G Sep 28 '18 at 13:26
  • Definetly not, the node version in the machine is 6.0.0 and cannot be upgraded. – gdm Sep 28 '18 at 13:28
  • Possible duplicate of [JavaScript ES6 promise for loop](https://stackoverflow.com/questions/40328932/javascript-es6-promise-for-loop) – Cody G Sep 28 '18 at 13:28
  • Why is this not a duplicate of this question? – Cody G Sep 28 '18 at 13:29
  • wow, you are right. Let me read that answer, ok? – gdm Sep 28 '18 at 13:30
  • I tried, but no luck. see the edit. – gdm Sep 28 '18 at 15:07
  • Can you use a generator function? – Cody G Sep 28 '18 at 15:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180945/discussion-between-giuseppe-and-cody-g). – gdm Sep 28 '18 at 15:14
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! `myAsyncFunc` should not do anything else than `return anotherAsync` (maybe you don't need your wrapper at all), and `p.then(_ => new Promise(resolve => { myAsyncFunc(data[i]); })` needs to be `p.then(_ => myAsyncFunc(data[i]))` – Bergi Sep 28 '18 at 15:45

1 Answers1

0

I solved by using async/await which, apparently, seems to solve the acrobatics with asynchronous function calls details of JS

function myAsyncFunc(data) {
     anotherAsync.then( () => return );
}
async function simulate(mode) {
    for(let i=0; i < tempModel[0].linear.length; i++)
    {
        let a = await myAsyncFunc(mode,i);
    } 
}
gdm
  • 7,647
  • 3
  • 41
  • 71