首页 > 解决方案 > 如何让 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. 我怎么能发出并行请求但让回调等待另一个?

标签: javascriptasynchronouspromisedata-race

解决方案


听起来你想要这样的东西

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(). 这个(大概)同步操作成为了somePromise 解决方案的一部分。other一旦 HTTP 请求完成,promise 就会解决。

一旦someother承诺都得到解决,请致电do_other_operation()


推荐阅读