javascript - Node.js foreach + 承诺
问题描述
我想打印arr=[1, 2, 3, 4]
如下。
1 101 2 102 3 103 4 104
但结果如下。
1 2 3 4 101 102 103 104
我的代码
var arr = [1, 2, 3, 4];
var promises = [];
arr.forEach(function(elem){
print(elem)
.then(addAndPrint)
}
)
function print(elem){
return new Promise(function(resolve, reject){
console.log(elem);
resolve(elem);
});
}
function addAndPrint(elem){
console.log(elem + 100);
}
我怎样才能得到我想要的结果?
解决方案
.then
s异步执行(类似于setTimeout(.., 0)
)(即使 Promise 立即解析),而 Promise 创建函数new Promise((res, rej) => {
同步运行。所以,如果你同步地创建了一堆promise ,比如forEach
在主线程结束之前,这些promise的块将在到达任何s之前立即运行。then
使用await
andreduce
或for..of
确保迭代以串行方式运行,而不是并行运行:
var arr = [1, 2, 3, 4];
var promises = [];
arr.reduce(async function(lastPromise, elem) {
await lastPromise;
return print(elem)
.then(addAndPrint)
}, Promise.resolve())
function print(elem) {
return new Promise(function(resolve, reject) {
console.log(elem);
resolve(elem);
});
}
function addAndPrint(elem) {
console.log(elem + 100);
}
推荐阅读
- ruby-on-rails - 具有多个用户的 Rails 模型
- php - 试图呼应 slug 的值,但由于某种原因它不起作用
- django - 如何使用pk重定向到页面
- java - 如何从数组列表中添加/删除多个对象
- react-native - 无法从 android 模拟器获取填充的 sqlite db
- openid-connect - 我们应该比较 Access Token 和 ID Token 中的“sub”声明吗?
- java - 复制类但覆盖现有的类导入
- python - “计数器”对象没有属性“计数”
- ruby-on-rails - Ruby Google Cloud PubSub 异步拉取返回 GRPC::DeadlineExceeded 错误
- python - Django按日历日期而不是发布日期订购事件