如何在 forEach 循环中等待 Promise [英] How to wait a Promise inside a forEach loop

查看:71
本文介绍了如何在 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();

这篇关于如何在 forEach 循环中等待 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆