javascript - for-loop 中的 Discord.js setTimeout 正在同时打印值,有没有办法让这个简单的程序工作
问题描述
我的代码是:
for (let i = 0; i <= 5; i++) {
delay(i);
}
function delay(i) {
setTimeout(() => console.log(`${i} is the number`), 2000);
}
我在 2 秒后得到的输出是:
0 是数字
1 是数字
2 是数字
3是数字
4是数字
5是数字
它们都在 2 秒后立即打印在一起,而我希望它们每个都在 2 秒后打印,例如:
0 是数字
(2秒后)
1 是数字
(2秒后)
2是数字.....
有什么办法让它工作吗?谢谢!!
解决方案
setTimeout
是一个非阻塞函数。for
循环不等待完成,delay
而是delay(i)
直接连续调用六次。
为了使这种情况有效,您可以使用async/await
Promise-ify setTimeout
:
(async () => {
for (let i = 0; i <= 5; i++) {
await delay(i);
}
})();
function delay(i) {
return new Promise(resolve => setTimeout(() => {
console.log(`${i} is the number`);
resolve();
}, 2000));
}
推荐阅读
- react-native - React-Native Jest PropType 测试
- java - 获取 JTextField 文本并在 JTextarea 上实时显示
- java - 如何从java中的firebase获取孩子的孩子的价值
- java - 错误:类中的构造函数不能应用于给定类型
- java - 我如何使用 Selenium 将以下兄弟元素计数放入变量中?
- javascript - AngularJS $http 不断在我的一个网址中添加斜杠
- reactjs - 在 React JS 中以状态将值数组附加到当前数组
- angular - 在 IE (Angular 5) 中打印 Blob 或 ArrayBuffer
- twilio - 如何在 twilio php 中执行拨号队列?
- c++ - 在 C++ 中读取 UTF-16 文件