How to wait a Promise inside a forEach loop(如何在 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 在初始化下一个之前解决:你可以通过 await 在 async 函数中对每个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 forEach 循环中等待 Promise
				
        
 
            
        - 400或500级别的HTTP响应 2022-01-01
 - 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 - addEventListener 在 IE 11 中不起作用 2022-01-01
 - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
 - Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
 - 失败的 Canvas 360 jquery 插件 2022-01-01
 - Fetch API 如何获取响应体? 2022-01-01
 - CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
 - Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
 - Flexslider 箭头未正确显示 2022-01-01
 
						
						
						
						
						