我正在使用一些承诺来获取一些数据,但我在项目中遇到了这个问题。
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");
};
Run Code Online (Sandbox Code Playgroud)
如果我在代码中调用 doStuff 函数,结果不正确,我预期的结果如下所示。
RESULT EXPECTED
a a
b First
c Second
The End b
First First
Second …Run Code Online (Sandbox Code Playgroud)