如何在 forEach 循环中等待 Promise

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

I'm using some Promises to fetch some data and I got stuck with this problem on a project.

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 函数,结果不正确,我期望的结果如下所示.

If I call the doStuff function on my code the result is not correct, the result I expected is shown below.

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".

At the end of the function no matter how I try, the variable s gets returned as "", I expected s to be "c".

推荐答案

听起来你想等待每个 Promise 在初始化下一个之前解决:你可以通过 awaitasync 函数中对每个 Promise 执行此操作(并且您必须使用标准的 for 循环以异步迭代 await):

It sounds like you want to wait for each Promise to resolve before initializing the next: you can do this by awaiting each of the Promises inside an async function (and you'll have to use a standard for loop to asynchronously iterate with 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:

await is only syntax sugar for Promises - it's possible (just a lot harder to read at a glance) to re-write this without 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();

相关文章