如何在 forEach 循环中等待 Promise

How to wait a Promise inside a forEach loop

我正在使用一些 Promises 来获取一些数据,但我在一个项目中遇到了这个问题。

example1 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo1');
  }, 3000);
});

example2 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo2');
  }, 3000);
});

doStuff = () =>  {
  const listExample = ['a','b','c'];
  let s = "";
  listExample.forEach((item,index) => {
    console.log(item);
    example1().then(() => {
        console.log("First");
        s = item;
    });
    example2().then(() => {
        console.log("Second");
    });
  });
  console.log("The End");
};

如果我在我的代码上调用 doStuff 函数,结果不正确,我预期的结果如下所示。

RESULT                EXPECTED
a                     a
b                     First
c                     Second
The End               b
First                 First
Second                Second
First                 c
Second                First
First                 Second
Second                The End

在函数的末尾,无论我如何尝试,变量 s 都返回为“”,我希望 s 为“c”。

听起来您想 等待 每个 Promise 解决后再初始化下一个:您可以通过 await 对每个 await Promises 在 async 函数中(并且您必须使用标准 for 循环与 await 异步迭代):

const example1 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo1');
  }, 500);
});

const example2 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo2');
  }, 500);
});

const doStuff = async () =>  {
  const listExample = ['a','b','c'];
  for (let i = 0; i < listExample.length; i++) {
    console.log(listExample[i]);
    await example1();
    const s = listExample[i];
    console.log("Fisrt");
    await example2();
    console.log("Second");
  }
  console.log("The End");
};

doStuff();

await 只是 Promises 的语法糖 - 可能 (乍一看更难阅读)重写这个没有 async/await:

const example1 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo1');
  }, 500);
});

const example2 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo2');
  }, 500);
});

const doStuff = () =>  {
  const listExample = ['a','b','c'];
  return listExample.reduce((lastPromise, item) => (
    lastPromise
      .then(() => console.log(item))
      .then(example1)
      .then(() => console.log("Fisrt"))
      .then(example2)
      .then(() => console.log('Second'))
  ), Promise.resolve())
    .then(() => console.log("The End"));
};

doStuff();

如果您不想在开始下一个承诺之前等待每个承诺完成;

您可以使用 Promise.all() 来 运行 在您的所有承诺都已解决之后;

example1 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo1');
  }, 3000);
});

example2 = () => new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo2');
  }, 3000);
});

doStuff = () => {
  const listExample = ['a','b','c'];
  let s = "";
  let promises = []; // hold all the promises
  listExample.forEach((item,index) => {
    s = item; //moved
    promises.push(example1() //add each promise to the array
    .then(() => {  
        console.log(item); //moved
        console.log("First");
    }));
    promises.push(example2() //add each promise to the array
    .then(() => {
        console.log("Second");
    }));
  });
  Promise.all(promises) //wait for all the promises to finish (returns a promise)
  .then(() => console.log("The End")); 
  return s;
};
doStuff();