javascript - 如何仅在第一个功能完成后才执行第二个功能?
问题描述
我有 2 个单独的函数,它们都在发出 GET 请求。完成后,我需要将 response1 中的数字与 response2 中的数字相加。所以基本上我想要制作第三个函数,它将前两个函数的结果相加。问题是第三个函数在第一个和第二个之前执行。
我尝试了回调,但似乎没有按预期工作。下面你可以找到一个简单的例子,我想在我的代码中实现它之前了解基础知识。我试过的回调示例:
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
功能和使用await
first()
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();
推荐阅读
- html - 如何在移动视图中对齐表格按钮中的文本
- flutter - 如何在flutter中在DecorationImage()中编写if else语句
- apache - 将 Solr 结果限制为 SAP hybris 中的类别
- reactjs - 为什么在使用 redux-thunk 时,内部函数会返回一些东西?
- google-sheets - 如何绕过 rept() 32000 最大字符限制?
- c# - 将 Json 反序列化为 C#
- elixir - 如何在 Elixir 中用最地道的方式做一系列验证
- java - 如何重构重复代码以创建 Intent?
- python - 进程以退出代码 -1073741819 (0xC0000005) - Rpy2 完成
- entity-framework - 使用多租户 .net 核心中的实体框架从模型更新数据库