【问题标题】:How to make a multiple api call on submission of a form in react如何在react中提交表单时进行多个api调用
【发布时间】:2020-05-27 16:28:27
【问题描述】:

我有一个包含 10 行(可能不同)数据的表单,提交时我需要为每一行进行 10 个(可能不同)api 调用。我正在使用 axios 进行 api 调用。如何以最佳和有效的方式一次单击进行多个 api 调用?。

【问题讨论】:

  • 为什么要做10次api调用,一次api调用就提交表单数据
  • 因为 api 一次只接收一项而不是全部,即它是更新项而不是全部更新。最好有更新所有的api,但我不能随意更改api。

标签: javascript reactjs promise axios


【解决方案1】:

您也可以使用 Bluebird。

import Bluebird from 'bluebird';

 deleteRequests = (requests) => {
       let promiseCollection = [];

        try {
            requests.map((request, index) => {
                    promiseCollection.push(axios.delete(request.API + request.ids));
            });
            return Bluebird.all(promiseCollection);
        }
        catch (error) {
        }
}

【讨论】:

    【解决方案2】:

    Axios 支持 Promise api,因此您可以使用 Promise.all 一次处理所有 10 个请求。这是一个小例子:

    const requests = [
      { url: "https://some.url", body: { some: "body" } },
      { url: "https://some.other.url", body: { some: "other body" } },
      // As many as you like
    ];
    
    const promises = requests.map(request => axios.post(request.url, request.body));
    const result = Promise.all(promises).catch(error => console.log(`Someting went wrong: ${error}`);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-19
      • 2021-12-06
      • 1970-01-01
      • 2018-10-11
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      相关资源
      最近更新 更多