You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何让setPending在所有并行网络请求完成后执行?

解决方案

问题根源

你的fetchDetails这类请求函数没有返回Promise,且fetchAll里没有等待异步请求完成就执行了setPending(false),导致pending状态提前关闭。同时原代码没利用Promise特性实现并行请求的等待逻辑。

步骤1:让每个请求函数返回Promise

修改fetchDetails(以及其他类似fetchContact的函数),让它们返回axios请求的Promise,这样才能被Promise.all捕获并等待:

const fetchDetails = (userId) => {
  // 添加return,返回axios请求的Promise
  return axios.post("/api/fetch/fetchDetails", {
    id: userId
  })
  .then((response) => {
    console.log(response.data)
    setName(response.data.name)
    setPreviewPhoto(response.data.profile_picture_url)
    setPhotoName(response.data.profile_picture_name)
    setPhotoFile(response.data.profile_picture_url)
  })
}

// 同理修改其他请求函数,比如fetchContact
const fetchContact = (userId) => {
  return axios.post("/api/fetch/fetchContact", {
    id: userId
  })
  .then((response) => {
    // 处理对应状态更新
    setContact(response.data)
  })
}

步骤2:修改fetchAll,用Promise.all并行等待所有请求

把fetchAll改成异步函数,通过Promise.all并行发起所有请求,等待全部完成后再更新pending状态,同时统一处理错误:

const fetchAll = async (userId) => {
  try {
    // 用Promise.all并行执行所有请求,数组中可添加任意多个请求函数
    await Promise.all([
      fetchDetails(userId),
      fetchContact(userId)
      // 继续添加其他需要并行的请求
    ])
  } catch (err) {
    console.log("请求出错:", err)
    // 可按需添加错误状态处理,比如setError(err)
  } finally {
    // 无论成功或失败,最后都关闭pending状态
    setPending(false)
  }
}

关键说明

  • Promise.all会同时发起所有请求,彻底避免瀑布流(前一个请求完成才发起下一个)的低效问题。
  • await会等待所有Promise都执行完成(resolve)后才继续后续逻辑,确保所有请求处理完毕后再关闭pending。
  • 若任意一个请求失败,Promise.all会立即进入catch块处理错误,最后在finally中关闭pending,避免用户一直看到加载状态。

内容的提问来源于stack exchange,提问作者Jon Nicholson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:03:03