亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓 JavsScript 回調等待另一個回調?

如何讓 JavsScript 回調等待另一個回調?

茅侃侃 2023-06-09 17:29:40
我需要同時進行兩個 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        });    });});在 C++ 中使用std::conditional_variable和以下偽(C++17 左右)代碼可以輕松地進行并行調用和等待另一個調用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 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

聽起來你想要這樣的東西


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承諾解決方案的一部分。other一旦 HTTP 請求完成,承諾就會解決。


一旦some和otherpromises 都解決了,調用do_other_operation()


查看完整回答
反對 回復 2023-06-09
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

使用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);

});

或者


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

});


查看完整回答
反對 回復 2023-06-09
  • 2 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號