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

React项目中如何在Fetch满足特定条件时返回拒绝状态的Promise

How to Make Fetch Return a Rejected Promise on Specific Conditions in React

Fetch only rejects its promise on network failures—it won’t reject for HTTP errors (like 404/500) or custom response conditions (like your data.code check). To trigger a rejection when your specific condition is met, you can manually throw an error (or return a rejected promise) inside your .then() chain. Here’s how to adjust your code:

Modified Code with Condition-Based Rejection

return fetch(controllerURI, { 
  method: 'post', 
  headers: { 'Content-Type': 'application/json; charset=utf-8' }, 
  body: JSON.stringify({ 
    userId: this.state.userEmailAndName.userId, 
    name: this.state.userEmailAndName.name, 
    newEmail: this.state.userEmailAndName.newEmail 
  }) 
})
// Optional but recommended: Handle HTTP errors first
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
  }
  return response.json();
})
// Check your custom data.code condition
.then(data => {
  // Replace this with your actual condition (e.g., data.code !== 200, data.code === "ERROR")
  if (data.code !== "SUCCESS") {
    // Throw an error to reject the promise chain
    throw new Error(`Request failed: ${data.message || `Code ${data.code}`}`);
  }
  // If condition isn't met, return data to continue the chain
  return data;
})
.catch(error => {
  // Handle the rejection here (update UI, show error message, etc.)
  console.error("Request rejected:", error.message);
  // Re-throw the error if you want upstream code to handle it too
  throw error;
});

How This Works

  • Throwing an error in a .then() handler converts the resolved promise to a rejected one, which immediately jumps to the nearest .catch() block.
  • Handling HTTP errors first ensures you catch issues like invalid endpoints or server errors before parsing the JSON response.
  • You can also use return Promise.reject(new Error("Message")) instead of throwing—both achieve the same result.

Example Usage in a React Component

If you’re using this in a form submit handler, you might wrap it in an async function for cleaner code:

handleEmailUpdate = async () => {
  try {
    const result = await fetch(...); // Use the modified fetch code above
    // If successful, update state or redirect
    this.setState({ successMessage: "Email updated successfully!" });
  } catch (error) {
    // Handle rejection here (show error to user)
    this.setState({ errorMessage: error.message });
  }
};

This approach gives you full control over when the promise should reject, aligning it with your app’s specific business logic.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:19:30