使用Promise和Fetch的数据获取和错误处理

本文探讨了Fetch API返回的Promise如何处理HTTP错误状态,强调了即使HTTP响应为404或500,Promise也不会被拒绝。fetch只在网络故障时拒绝。通过Response.ok属性判断HTTP响应是否成功,结合Promise处理数据获取和错误。示例代码展示了如何在http.js和app.js中使用fetch获取和处理JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拿post和delete举例说明吧

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

http.js这个文件用来处理fetch请求,app.js设置初始的参数
关于fetch比较重要的是,fetch返回一个promise,fetch() API 仅在遇到"网络错误"时拒绝承诺,尽管这通常意味着权限问题或类似问题。基本上,fetch() 将拒绝承诺,如果用户脱机,或发生一些不太可能的网络错误,如 DNS 查找失败。
如果遇到网络故障,fetch() promise 将会 reject,带上一个 TypeError 对象。虽然这个情况经常是遇到了权限问题或类似问题——比如 404 不是一个网络故障。想要精确的判断 fetch() 是否成功,需要包含 promise resolved 的情况,此时再判断 Response.ok 是不是为 true。

好消息是,fetch提供了一个简单的 OK 标志,指示 HTTP 响应的状态代码是否处于成功范围内。例如,以下代码日志"错误:内部服务器错误(…)":

fetch("http://httpstat.us/500")
    .then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        console.log("ok");
    }).catch(function(error) {
        console.log(error);
    });

我们可以用fetch返回给我们的response里的ok属性,如果有错误就是true,那么有错误就throw这个错误,没有就返回reponse.json();,如果不用json的话fetch会返回response对象,我们并没法使用,如果打开proto属性看会看到json方法这样就可以获得具体的数据。
然后接着使用.then获取上一步的.json()然后resolve,我们就可以从app.js中使用.then获取到resolved的数据

http.js

class HTTP{  //es6 class
	handleError(response){  //handle the error function
		if (!response.ok) {
      		throw new Error(response.status);
    }
    		return response.json();
		}
	post(url,data){
		return new Promise((resolve,reject)=>{
			fetch(url,{
						method:'POST',
						headers:{
						'Content-Type':'application/json'
						},
						body:JSON.stringify(data)
			}).then(this.handleError)
				.then(data => resolve(data))
					.catch(console.log)
					})
				}
   delete(url) {
    	return new Promise((resolve, reject) => {
      		fetch(url, {
				        method: "DELETE",
				        headers: {
				          "Content-Type": "application/json"
				        }
				      })
				        .then(this.handleErrors)
				        .then(() => resolve("Deleted"))
				        .catch(console.log);
    });
  }
		
		}


app.js

const http = new HTTP();
const data = {
  name: "sam yao",
  username: "moviegoer",
  email: "yaob@miamioh.edu"
};
http
  .post("https://jsonplaceholder.typicode.com/users", data)
  .then(data => console.log(data));
http
  .delete("https://jsonplaceholder.typicode.com/users/2")
  .then(data => console.log(data));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值