我正在使用一些Promise()函数来获取一些数据,但我在项目中陷入了这个问题。
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函数,则结果不正确,下面显示了我期望的结果。
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”。
答案 0 :(得分:2)
听起来好像您希望每个Promise
都先等待解决,然后再初始化下一个:您可以通过await
分别Promise
来完成此操作放在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
仅是Promise
s的语法糖-它可能 (一目了然很难阅读),而无需使用{{1} } / async
:
await
答案 1 :(得分:0)
如果您不想在开始下一个承诺之前不等待每个诺言完成;
在您所有的诺言都解决之后,您可以使用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();