在 promise 完成之前退出 forEach

Exiting the forEach before promise is done

我试图在 forEach 循环内调用请求,但我的代码在循环完成之前退出循环。有没有办法确保循环在执行下一个代码之前完成? (我对承诺比较陌生)

我的代码遵循以下格式:

let arr = [1, 2, 3, 4, 5, 6];

arr.forEach(num => {
  return request('http://google.com')
    .get('/')
    .then(() => {
      console.log(num);
    });
});
console.log('HERE');

这段代码^记录

HERE
1
2
6
4
5
3

(数字是随机排列的,这对我来说并不重要)

但我想让它记录下来

1
2
3
4
5
6
HERE

我该怎么做?

在这种情况下你不能使用forEach

相反,由于您使用的是基于 promise 的并发,因此您必须将每个请求变成一个 Promise (arr.map(num => ...)),然后将它们全部包装在 Promise.all 中,它本身returns 在所有包装的承诺解决后解决的承诺。

let arr = [1, 2, 3, 4, 5, 6];

Promise.all(
  arr.map(num =>
    request("http://google.com")
      .get("/")
      .then(() => {
        console.log(num);
      })
  )
).then(() => {
  console.log("HERE");
});

这里是另一个例子。您也可以使用 for

let array = [1, 2, 3, 4, 5, 6];
async function processArray(arr){
  for (const num of array) {
    await request('http://google.com').get('/');
    console.log(num);
  }
  console.log('Done!');
}

processArray(array);