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

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

需要依次調用多個api,在javascript中一個接一個

需要依次調用多個api,在javascript中一個接一個

慕標琳琳 2022-11-11 16:21:20
我需要在javascript中一個接一個地依次調用多個api。一個人的反應可能需要作為另一個人的輸入。有人可以建議或提供示例代碼。我嘗試使用 .fetch() api,但發現很難將一個 api 的響應傳遞給另一個。
查看完整描述

2 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

利用apipromises原生返回fetch,多個請求可以一個接一個的鏈接


var result = fetch('api/url1') // First request

    .then(function (response) {

        return response.json();

    })

    .then(function (data) {

        var secondId = data.someId

        return fetch('api/url2' + secondId); // Second request

    })

    .then(function (response) {

        return response.json();

    })

    .then(function (data) {

        var thirdId = data.someId

        return fetch('api/url3' + thirdId); // Third request

    })

    .then(function (response) {

        return response.json();

    })

    .then(function (data) {

        // Response of third API

    })

    .catch(function (error) {

        console.log('Error', error)

    })


查看完整回答
反對 回復 2022-11-11
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

盡管答案已被接受,但請嘗試async await這樣。


(async () => {

  // first

  const res = await fetch("https://reqres.in/api/users/1");

  const result1 = await res.json();

  

  console.log("Result 1", result1);

  

  // some logic ...

  

  // second 

  const res2 = await fetch("https://reqres.in/api/users/2");

  const result2 = await res2.json();

  

  console.log("Result 2", result2);

  // ... so on ...

})();


查看完整回答
反對 回復 2022-11-11
  • 2 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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