首页 > 解决方案 > 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);
}

我怎样才能得到我想要的结果?

标签: javascriptnode.jspromise

解决方案


.thens异步执行(类似于setTimeout(.., 0))(即使 Promise 立即解析),而 Promise 创建函数new Promise((res, rej) => {同步运行。所以,如果你同步地创建了一堆promise ,比如forEach在主线程结束之前,这些promise的块将在到达任何s之前立即运行。then

使用awaitandreducefor..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);
}


推荐阅读