React.js 中 Map() 完成多个 Fecth API 请求后执行函数

问题描述 投票:0回答:1

在这里与承诺搏斗......

我的用户发出一个请求,需要在后端进行多个 REST 调用。我将用户发出的每个请求和两个 REST 响应作为一个项目存储在“记录”数组中,如下所示:

[
  {
    call:userRequest,
    responses: [
        {
          source:source1
          response:responseText
        },
        {
          source:source2
          response:responseText
        }
      ]
  }
]

我使用映射函数进行多个 REST API 调用。我使用“setThisCall”方法处理每个响应,该方法将每个响应的详细信息添加到数组“thisCall”中。完成后,“thisCall”用作“records”数组中“responses”的值分配给“thisCall”。

await Promise.all(urls.map(async url =>  {
  
  fetch(url, { 
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: messageBody
  })
  .then((response) => response.json())
  .then((data) => {
    setThisCall(prev => ([ //sets thisCall
      ...prev,
      {
        source: source,
        response: data.body
      }
    ]))
  })
})).then(()=>{
  console.log("now adding to records")
  setRecords(prev => ([ //sets records
    {
      call: requestText,
      reponses: thisCall
      },
      ...prev
    ]))
  })

我尝试使用 Promise.all() 让映射函数完成效果并处理响应,并使用“then”将调用添加到下一个“记录”项。

但是最终的“then”在“thisCall”构建之前触发,导致“records”中的“response”值为空。

tl;dr - 如何在其余代码完成后执行“setRecords”?

reactjs promise fetch-api
1个回答
0
投票
await Promise.all(
  urls.map((url) => {
    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: messageBody,
    })
      .then((response) => response.json())
      .then((data) => {
        setThisCall((prev) => [
          //sets thisCall
          ...prev,
          {
            source: source,
            response: data.body,
          },
        ]);
      });
  })
);

console.log("now adding to records");
setRecords((prev) => [
  //sets records
  {
    call: requestText,
    reponses: thisCall,
  },
  ...prev,
]);
© www.soinside.com 2019 - 2024. All rights reserved.