繁体   English   中英

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

[英]How to make a JavsScript callback wait for another callback?

我需要同时进行两个 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承诺解决方案的一部分。 一旦 HTTP 请求完成, other承诺就会解决。

一旦some承诺和other承诺都得到解决,调用do_other_operation()

使用承诺所有

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);
});

或者

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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM