我有 2 个独立的函数,两个函数都在发出 GET 请求。 完成后,我需要将响应 1 中的数字与响应 2 中的数字相加。所以基本上我想要创建第三个函数,它将把前两个函数的结果相加。 问题是第三个函数在第一个和第二个函数之前执行。
我尝试了回调,但似乎没有按预期工作。下面您可以找到一个简单的示例,我想在我的代码中实现它之前了解基础知识。我尝试过的回调示例:
function first(callback){
setTimeout(function(){
console.log(1);
}, 500);
callback()
}
function second(){
console.log(2);
}
function third(){
first(second);
}
third();
没有回调的示例:
function first(){
setTimeout(function(){
console.log(1);
}, 500);
}
function second(){
console.log(2);
}
function third(){
first();
second();
}
third();
https://jsfiddle.net/u8a592pz/
当前该函数执行为:
2
1
我想要得到什么:
1
2
最佳答案
将 first
的内容包装在 Promise 中并返回它。并将 third
设置为 async
函数,并在 first()
之前使用 await
function first(){
return new Promise(res => {
setTimeout(function(){
console.log(1);
res();
}, 500);
})
}
function second(){
console.log(2);
}
async function third(){
await first();
second();
}
third();
关于javascript - 如何仅在第一个函数完成后才执行第二个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55678915/