簡體   English   中英

React JS 中的異步 API 獲取

[英]Async API Fetch in React JS

我在 nodeJS express 中創建了兩個 POST 服務

  • http://localhost:3001 - 此服務具有正文請求 {order:"123"} 方法 POST 和 setTimeout 為 5000
  • http://localhost:3001/details - 此服務沒有任何正文請求或 setTimeout

以上兩個服務都給出了回應

  • 第一反應是:訂單代碼:123
  • 第二個響應是 JSON 的訂單詳細信息:{'Date':'2020-05-12', 'amount':'20'}

我必須創建一個 React JS 應用程序來獲取這兩個服務。 但是我要求當我們同時調用兩個服務時,第二個服務不應該等待第一個服務完成。

以下是我在 REACT JS 中對服務的調用

const loadOrders = () =>{
   fetch("http://localhost:3001",{
     method:'POST',
     body: JSON.stringify({orderReferenceCode: 'GBP-000237453'}),
     headers: {
      "Content-type": "application/json; charset=UTF-8"
     }
     })
   .then(res => (res.ok ? res : Promise.reject(res)))
   .then(res => res.json())
 }

 const loadOrdersDetails = () =>{
   fetch("http://localhost:3001/details",{
     method:'POST',
     headers: {
      "Content-type": "application/json; charset=UTF-8"
     }
     })
   .then(res => (res.ok ? res : Promise.reject(res)))
   .then(res => res.json())
 }

我能做些什么來異步這個調用???

您可以使用 promise.all 這將確保兩個 API 將獨立執行,並且您將在這兩個 API 執行后獲得結果

 //first api which is returning promise

 const loadOrders = () =>{
   new Promise((resolve, reject) => {
        fetch("http://localhost:3001",{
          method:'POST',
          body: JSON.stringify({orderReferenceCode: 'GBP-000237453'}),
      headers: {
          "Content-type": "application/json; charset=UTF-8"
      }
        })
   .then(res => (res.ok ? res : reject(res)))
   .then(res => resolve(res.json()))
   });
   
 }

 //second api which is returning promise
 const loadOrdersDetails = () =>{
   new Promise((resolve, reject) => {
        fetch("http://localhost:3001/details",{
          method:'POST',
      headers: {
          "Content-type": "application/json; charset=UTF-8"
      }
     })
     .then(res => (res.ok ? res : reject(res)))
     .then(res => resolve(res.json()))
   })
 }
 
 Promise.all([loadOrders, loadOrdersDetails]).then((res) => {
    //here in res you will get reponse in array as output json from both the api [{},{}]
});

很簡單:

loadOrders();
loadOrdersDetails();

function 是按順序調用的,但有效流程取決於回調,回調是異步的。

但是,如果需要,您必須對 UI 采取適當的方法來管理結果。

如果您只是像馬里奧·維納里(Mario Vernari)在另一個答案中建議的那樣,一個接一個地調用它們,那么您將同時調用它們(這意味着第二個調用不會等待第一個調用完成后再發送)。

我想補充的是,您可能希望同時並行地觸發兩個請求,然后等待它們完成對它們兩個結果的處理。

為了做到這一點,有兩種方法:

使用Promise.all

Promise.all([
  loadOrders(),
  loadOrdersDetails(),
]).then(([orderCode, orderDetails]) => {
    // Do something
}).catch((err) => {
    console.log(err);
}); 

使用async/await

try {
  let [orderCode, orderDetails] = await Promise.all([
    loadOrders(),
    loadOrdersDetails(),
  ]);

    // Do something
  );
}
catch(err) {
  console.log(err);
};

此外,您應該使兩個加載函數都返回 Promise。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM