javascript - 如何让 JavsScript 回调等待另一个回调?
问题描述
我需要同时进行两个 API 调用。并且其中一个回调必须在另一个之前执行。但是按顺序进行调用会很慢并且对用户体验不利:
axios.get("/get_some_data").then(function(resp) {
do_some_operation();
axios.get("/get_other_data").then(function(resp) {
do_other_operation(); // Needs /get_some_data and /get_other_data both be done
});
});
});
使用std::conditional_variable和以下伪(C++17 ish)代码在 C++ 中可以轻松地进行并行调用并等待另一个调用
std::conditional_variable cv;
std::mutex mtx;
get_request("/get_some_data",[&](auto&& resp){
do_some_operation();
// Notify that the operation is complete. The other callback can proceed
cv.notify_all();
});
get_request("/get_other_data",[&](auto&& resp){
// Wait until someone notify the previous task is done
std::lock_guard lk(mtx);
cv.wait(lk);
do_other_operation();
});
我在各种网站上搜索过。但我不认为 JavaScript 附带任何类似的东西std::conditional_variable
,甚至没有std::mutex
. 我怎么能发出并行请求但让回调等待另一个?
解决方案
听起来你想要这样的东西
const some = axios.get("/get_some_data").then(res => {
do_some_operation()
return res
})
const other = axios.get("/get_other_data")
Promise.all([some, other]).then(([ someRes, otherRes ]) => {
do_other_operation()
})
这将并行调用两个 URL。
当第一个解决时,它将调用do_some_operation()
. 这个(大概)同步操作成为了some
Promise 解决方案的一部分。other
一旦 HTTP 请求完成,promise 就会解决。
一旦some
和other
承诺都得到解决,请致电do_other_operation()
推荐阅读
- kubernetes - 如何向 kubelet 添加标志
- javascript - 如何将数据目标用于不同的组件?
- vue.js - 强制使用旧版本的 vuejs devtools 或下载旧版本
- ios - 我如何以团队成员的身份提交 TestFlight 构建
- mysql - 我的目标是合并这两个查询。我在以单独的方式执行时存在差异
- python - 提取python中连续行之间的差异
- excel - “锁定功能”在 vba 中不再起作用
- laravel - Laravel Eloquent - 只有一种
- scala - 使用扩展方法规避差异检查
- apache-kafka - Kafka 连接:提供了配置 XXX,但不是 AdminClientConfig 中的已知配置