NodeJS 中使用 async/await 等效于 Python 的 time.sleep()
安装 sleep-promise 包:
nodejs_sleep_async_example.sh
npm install --save sleep-promise然后你可以使用
nodejs_sleep_usage.js
const sleep = require('sleep-promise');
// 在任何异步函数中:
await sleep(2000); // 等待 2000 毫秒
完整示例:
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
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow