zhu*_*per 3 javascript asynchronous promise async-await
首先,我必须提到我已经在stackoverflow中查看了很多问题,但很多问题都没有回答我的问题.更不用说很多甚至没有答案.
如何实现以下功能,确保完成functionB()后执行functionA()?
注意:我不想将我的异步函数转换为,new Promise(resolve=>{...})
因为我必须转换someServiceThatMakesHTTPCall()调用堆栈中的以及任何其他异步函数,这是一个很大的改变.
function functionThatCannotHaveAsyncKeyword() {
functionA()
.then(async function() {
await functionB();
})
.then(function() {
console.log('last');
});
}
async function functionA() {
console.log('first');
await someServiceThatMakesHTTPCall();
}
async function functionB() {
console.log('second');
await someServiceThatMakesHTTPCall();
}
Run Code Online (Sandbox Code Playgroud)
用你的方法await在async then回调将工作,但它是不必要的复杂,如果所有你想要做的是调用async函数有它的结果通过链传播.但是,如果你正在做其他事情并希望async函数的语法优势,那很好.我马上回过头来看看.
async 函数返回promises,所以你只需返回调用函数的结果:
function functionThatCannotHaveAsyncKeyword() {
functionA()
.then(function() {
return functionB(someArgument);
})
.then(function() {
console.log('last');
}); // <=== Note: You need a `catch` here, or this function needs
// to return the promise chain to its caller so its caller can
// handle errors
}
Run Code Online (Sandbox Code Playgroud)
如果你想传递functionA分辨率值functionB,你可以更直接地做到:
functionA()
.then(functionB)
// ...
Run Code Online (Sandbox Code Playgroud)
当您从then回调中返回承诺时,调用创建的承诺将从您返回的承诺开始then.
例:
const wait = (duration, ...args) => new Promise(resolve => {
setTimeout(resolve, duration, ...args);
});
async function functionA() {
await wait(500);
return 42;
}
async function functionB() {
await wait(200);
return "answer";
}
functionB()
.then(result => {
console.log(result); // "answer"
return functionA();
})
.then(result => {
console.log(result); // 42
})
.catch(error => {
// ...handle error...
});Run Code Online (Sandbox Code Playgroud)
使用async then回调回到你的方法:这也有效,当你做更多的东西时有意义:
const wait = (duration, ...args) => new Promise(resolve => {
setTimeout(resolve, duration, ...args);
});
async function functionA() {
await wait(500);
return 42;
}
async function functionB() {
await wait(200);
return "answer";
}
functionB()
.then(async (result) => {
console.log(result); // "answer"
const v = await functionA();
if (v < 60) {
console.log("Waiting 400ms...");
await wait(400);
console.log("Done waiting");
}
console.log(v); // 42
})
.catch(error => {
// ...handle error...
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1731 次 |
| 最近记录: |