Combination of async function + await + setTimeout

The Solution to Combination of async function + await + setTimeout is

Your sleep function does not work because setTimeout does not (yet?) return a promise that could be awaited. You will need to promisify it manually:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
async function sleep(fn, ...args) {
    await timeout(3000);
    return fn(...args);

Btw, to slow down your loop you probably don't want to use a sleep function that takes a callback and defers it like this. I recommend:

while (goOn) {
  // other code
  var [parents] = await Promise.all([
  // other code

which lets the computation of parents take at least 5 seconds.

~ Answered on 2015-10-23 00:21:15

Most Viewed Questions: