javascriptnode.jstypescriptecmascript-2018

"Sleep" execution inside asynchronous iteration "for await" (ES2018)


I am using asynchronous iteration for getting items from DynamoDB. For every iteration (item) I execute some http requests. I need to "sleep" 1 second in every iteration in order to limit the request flow. I tried with promisify(setTimeout) but the execution stops.

const sleep = require('util').promisify(setTimeout)

for await (const item of mapper.scan(MyDomainObject)) {

    await sleep(1000);   //This doesn't work
    // do some http requests
}

What it's the proper way to "sleep" inside a "for await" interation?


Solution

  • I figured it out. The problem was that I was executing the code with Jest. When I executed the code normally the above code works perfectly. Thanks to Noseratio answer I looked elsewhere. I was too focused in the for await.