如何使JavsScript回调等待另一个回调?

时间:2020-10-26 02:31:20

标签: javascript asynchronous promise data-race

我需要同时进行两个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 ++中使用以下伪(C ++ 17 ish)代码,可以很容易地进行并行调用并等待另一个调用

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之类的东西。我该如何发出并行请求,但使回调等待另一个请求?

2 个答案:

答案 0 :(得分:2)

听起来像您想要的东西

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承诺解决方案的一部分。 HTTP请求完成后,other承诺就会解决。

someother的诺言都得到解决后,致电do_other_operation()

答案 1 :(得分:1)

使用promise all

Promise.all([
  get_request("/get_some_data"),
  get_request("/get_other_data")
]).then( function(responses) {
  console.log(responses);
  // do what you want
  do_some_operation();
  do_other_operation();
}).catch(function(error) { 
  console.error(error.message);
});

OR

Promise.all([
  get_request("/get_some_data").then(function (resp) {
    do_some_operation();
    return resp;
  },
  get_request("/get_other_data")
]).then( function(responses) {
  console.log(responses);
  // do what you want
  do_other_operation();
}).catch(function(error) { 
  console.error(error.message);
});
相关问题