首先,我不得不提一下,我已经在 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();
}
最佳答案
您使用 await
的方法在 async
then
回调将起作用,但如果您只想调用 async
,它会变得不必要地复杂。函数并使其结果通过链传播。但是,如果您正在做其他事情并想要 async
的语法优势功能,没问题。我稍后再谈。async
函数返回 promise ,因此您只需返回调用函数的结果:
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
}
如果你想通过functionA
的分辨率值转换为 functionB
,你可以更直接地做到这一点:functionA()
.then(functionB)
// ...
当您从 then
返回 promise 时回调,调用 then
创建的 promise 已解决您返回的 promise :它将等待另一个 promise 解决,然后以相同的方式解决。例子:
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...
});
使用
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...
});
关于javascript - js - 如何在 Promise .then() 中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901478/