I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working:
async function as
If you would like to use the same kind of syntax as setTimeout
you can write a helper function like this:
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
You can then call it like so:
const doStuffAsync = async () => {
await setAsyncTimeout(() => {
// Do stuff
}, 1000);
await setAsyncTimeout(() => {
// Do more stuff
}, 500);
await setAsyncTimeout(() => {
// Do even more stuff
}, 2000);
};
doStuffAsync();
I made a gist: https://gist.github.com/DaveBitter/f44889a2a52ad16b6a5129c39444bb57
The following code works in Chrome and Firefox and maybe other browsers.
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep(fn, ...args) {
await timeout(3000);
return fn(...args);
}
But in Internet Explorer I get a Syntax Error for the "(resolve **=>** 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'd rather recommend to do something like
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()
.
const sleep = require('util').promisify(setTimeout)
const sleep = m => new Promise(r => setTimeout(r, m))
(async () => {
console.time("Slept for")
await sleep(3000)
console.timeEnd("Slept for")
})()
await setTimeout(()=>{}, 200);
Will work if your Node version is 15 and above.