Combination of async function + await + setTimeout
Your sleep
function does not work because setTimeout
does not (yet?) return a promise that could be await
ed. 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([ listFiles(nextPageToken).then(requestParents), timeout(5000) ]); // other code}
which lets the computation of parents
take at least 5 seconds.
The quick one-liner, inline way
await new Promise(resolve => setTimeout(resolve, 1000));
Since Node 7.6, you can combine the functions promisify
function from the utils module with setTimeout()
.
Node.js
const sleep = require('util').promisify(setTimeout)
Javascript
const sleep = m => new Promise(r => setTimeout(r, m))
Usage
(async () => { console.time("Slept for") await sleep(3000) console.timeEnd("Slept for")})()