and*_*iro 4 javascript asynchronous promise es6-promise fetch-api
我正在使用一些承诺来获取一些数据,但我在项目中遇到了这个问题。
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 Second
First c
Second First
First Second
Second The End
Run Code Online (Sandbox Code Playgroud)
在函数末尾,无论我如何尝试,变量 s 都会返回为“”,我期望 s 为“c”。
听起来您想在初始化下一个之前等待每个Promise解决:您可以通过ing 函数内的await每个s 来完成此操作(并且您必须使用标准循环来异步迭代):Promiseasyncforawait
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();Run Code Online (Sandbox Code Playgroud)
await只是Promises 的语法糖 -可以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();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8766 次 |
| 最近记录: |