javascript - 如何在 while(JavaScript/Node.js) 中使用 Promise?
问题描述
我正在尝试使用 promise 和 while (JavaScript/Node.js) 依次重复执行多个进程。然而,promise 函数没有被执行(即所有的 console.log() 都不会显示)。
为什么 promise 函数在 while 中从未执行?
另外,如何按顺序重复显示一些 console.log() ?
var count = 0;
while(count < 5) {
Promise.resolve()
.then(function () {
return new Promise(function(resolve, reject) {
console.log('func1()...');
resolve('OK');
});
})
.then(function(value) {
return new Promise(function(resolve, reject) {
console.log('func2()...');
resolve('OK');
});
})
.then(function (value) {
console.log('func3()...');
count++;
}).catch(function (error) {
console.log(error);
});
}
解决方案
.then()
仍然是一个异步回调,在这里查看消息的顺序:
Promise.resolve().then(()=>console.log("got resolved"));
console.log("got here");
您可以做的一件事是将代码包装成async function
:
async function test(){
var count = 0;
while(count < 5) {
await Promise.resolve()
.then(function () {
return new Promise(function(resolve, reject) {
console.log('func1()...');
resolve('OK');
});
})
.then(function(value) {
return new Promise(function(resolve, reject) {
console.log('func2()...');
resolve('OK');
});
})
.then(function (value) {
console.log('func3()...');
count++;
}).catch(function (error) {
console.log(error);
});
}
}
test();
推荐阅读
- homebrew - 如何重命名自制水龙头
- database - 在 Graph 数据库中执行软删除的最佳方法是什么?
- bash - Cloudinit 能否用于自动化复杂的配置,例如 UFW 和 Apache
- javascript - 使用 vuetify 中的 VMenu 和渲染功能(作用域插槽)
- excel - 将过滤后的偏移值复制粘贴到不同的工作表中
- python - Matplotlib 在现有线上绘制点,仅通过知道 x 值
- reactjs - 从对象集合返回特定数组
- python - 根据另一列的值在列内求和
- excel - Excel - 将 Salesforce 报表中的数据导入现有表格
- python - 饥饿游戏问题