然后使用数组链

时间:2018-10-31 17:02:23

标签: javascript node.js

我正在寻找一种类似于Promise.all的将多个Promises链接在一起的方法,除了我希望每个对象都等待最后一个。我敢肯定这可能已经得到了回答,但我认为我不知道该怎么用Google。

function output(msg) {
 return new Promise((resolve,reject) => {
  console.log(msg);
  resolve();
 });
}

output('1st').then(() => {
 output('2nd').then(() => {
  output('3rd').then(() => {
   console.log('done')
  });
 });
});

// I want to be able to build from an array of length n
const msgs = ['1st','2nd','3rd'];

for(let i = 0; i < msgs.length;i++){
 // Not sure what to do here
 output(msgs[i]).then(() => {
  output(msgs[i+1]);
 });
}

2 个答案:

答案 0 :(得分:0)

您可以像这样链接它们,以避免像地狱般嵌套:

output('a')
    .then(a_out => output('b'))
    .then(b_out => output('c'))
    .then(c_out => console.log('all done'));

以及Promise<T>[]的序列:

let loopback = (arr, i=0) => {
    return arr[i].then(() => {
        if (i < arr.length - 1)
            return loopback(arr, i+1);
    });
};

let last = loopback(load);

答案 1 :(得分:0)

您可以在数组上使用类似forEach的循环,并在await内使用async function

function output(msg) {
 return new Promise((resolve,reject) => {
  console.log(msg);
  resolve();
 });
}
const msgs = ['1st','2nd','3rd'];
function ArrPromiseAll(arr) {
  arr.forEach(async function(i) {
    await output(i);
  });
  console.log("Done All.");
}
ArrPromiseAll(msgs);

输出:

1st
2nd
3rd
Done All.