如何在 NodeJS 中使用 async/await 睡眠

在 NodeJS 中使用 async/await 睡眠的最简单方法是 sleep-promise 包:

npm_install_sleep_promise.sh
npm install --save sleep-promise

使用该包你可以简单地使用 await sleep(milliseconds) 语法,如下所示:

sleep_example.js
const sleep = require('sleep-promise');

// 在任何异步函数中:
await sleep(2000); // 等待 2000 毫秒

注意此 sleep() 变体是完全异步的,IO 和其他异步操作仍然能够在后台继续 - sleep() 不会阻塞 NodeJS 进程。

完整示例:

sleep_full_example.js
const sleep = require('sleep-promise');

(async () => {
    console.log("This prints immediately");
    await sleep(2000);
    console.log("This prints 2 seconds later");
})();

Check out similar posts by category: Javascript, NodeJS