如何在forEach循环中等待Promise [英] How to wait a Promise inside a forEach loop
问题描述
我正在使用一些Promise()函数来获取一些数据,但我在项目中陷入了这个问题.
I'm using some Promise() functions 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("Fisrt");
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 bellow.
RESULT EXPECTED
a a
b First
c Second
The End b
Fisrt First
Second Second
Fisrt c
Second First
Fisrt 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
之前为每个 Promise
等待 :您可以通过 async
函数中的 Promise
中的每个 Promise
来执行此操作(并且您必须使用标准的 for
循环以 await
)进行异步迭代:
It sounds like you want to wait for each Promise
to resolve before initializing the next: you can do this by await
ing each of the Promise
s 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
只是 Promise
s的语法糖-重新编写 possible (很难看一眼)这没有 async
/ await
:
await
is only syntax sugar for Promise
s - 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屋!