Update Jan 2021: You can even do it in the Node REPL interactive using --experimental-repl-await
flag
$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.
A new answer to an old question. Today ( Jan 2017 June 2019) it is much easier. You can use the new async/await
syntax.
For example:
async function init() {
console.log(1);
await sleep(1000);
console.log(2);
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
For using async/await
out of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmony
flag.
Update June 2019: By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.
Update May 2020:
Soon you will be able to use the await
syntax outside of an async function. In the top level like in this example
await sleep(1000)
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
The proposal is in stage 3.
You can use it today by using webpack 5 (alpha),
More info:
- Harmony Flag in Nodejs: https://nodejs.org/en/docs/es6/
- All NodeJS Version for download: https://nodejs.org/en/download/releases/