Victor Marchuk Victor Marchuk - 1 year ago 70
Javascript Question

Make async/await loop execute in order

I have a loop that looks like that:

newThreadIds.map(async function(id) {
let thread = await API.getThread(id);
await ActiveThread.findOneAndUpdate({number: id}, {posts: thread.posts}, {upsert: true}).exec();
await Q.delay(1000);
});


The problem is that each iteration executes asynchronously and I would like there to be a 1 second delay between them. I know how to do it with promises, but it looks ugly and I would prefer to do it with async/await and as little nesting as possible.

Answer Source

I've figured it out:

    for (let id of newThreadIds) {
      let thread = await API.getThread(id);
      await ActiveThread.findOneAndUpdate({number: id}, {posts: thread.posts}, {upsert: true}).exec();
      await Q.delay(1000);
    }

It's probably the best way to it with ES2015 and async/await.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download