简体   繁体   English

React JS 中的异步 API 获取

[英]Async API Fetch in React JS

I have created two POST services in nodeJS express我在 nodeJS express 中创建了两个 POST 服务

  • http://localhost:3001 - This service has body request {order:"123"} with method POST & setTimeout for 5000 http://localhost:3001 - 此服务具有正文请求 {order:"123"} 方法 POST 和 setTimeout 为 5000
  • http://localhost:3001/details - This service doesn't have any body request or setTimeout http://localhost:3001/details - 此服务没有任何正文请求或 setTimeout

Both above service give a response以上两个服务都给出了回应

  • First Response is: Order Code:123第一反应是:订单代码:123
  • Second Response is JSON of Order Details: {'Date':'2020-05-12', 'amount':'20'}第二个响应是 JSON 的订单详细信息:{'Date':'2020-05-12', 'amount':'20'}

I have to create a React JS app to fetch both the services.我必须创建一个 React JS 应用程序来获取这两个服务。 But I require that when we call both services simultaneously, the second service shouldn't wait for the first service to complete.但是我要求当我们同时调用两个服务时,第二个服务不应该等待第一个服务完成。

Below is my call for the service in 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())
 }

What can I do to async this call's???我能做些什么来异步这个调用???

You can use promise.all this will make sure that both the API's will get executed independently and also you will get result after both these API's get executed您可以使用 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 [{},{}]
});

As simple as:很简单:

loadOrders();
loadOrdersDetails();

The function are called in sequence, but the effective flow it depends on the callback, which will be asynchronous. function 是按顺序调用的,但有效流程取决于回调,回调是异步的。

However, you must take an appropriate approach for the UI in order to manage the results, if you need them.但是,如果需要,您必须对 UI 采取适当的方法来管理结果。

If you just call them one after the other, as Mario Vernari suggested on the other answer, you will be calling both of them simultaneously (meaning the second call won't wait for the first one to be finished before being sent).如果您只是像马里奥·维纳里(Mario Vernari)在另一个答案中建议的那样,一个接一个地调用它们,那么您将同时调用它们(这意味着第二个调用不会等待第一个调用完成后再发送)。

What I wanted to add is that you probably want to fire both request simultaneosly, in parallel, but then wait for both of them to finish to do something with the result of both of them.我想补充的是,您可能希望同时并行地触发两个请求,然后等待它们完成对它们两个结果的处理。

In order to do that, there two approaches:为了做到这一点,有两种方法:

Using Promise.all使用Promise.all

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

Using async/await使用async/await

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

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

Additionally, you should make both load functions to return a Promise instead.此外,您应该使两个加载函数都返回 Promise。

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

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