我有一个HTTP API,无论成功还是失败,它都会返回JSON数据。失败示例如下所示:~ ◆ http get http://localhost:5000/api/isbn/2266202022 HTTP/1.1 400 BAD REQUESTContent-Length: 171Content-Type: application/jsonServer: TornadoServer/4.0{ "message": "There was an issue with at least some of the supplied values.", "payload": { "isbn": "Could not find match for ISBN." }, "type": "validation"}我想要在JavaScript代码中实现的是这样的:fetch(url) .then((resp) => { if (resp.status >= 200 && resp.status < 300) { return resp.json(); } else { // This does not work, since the Promise returned by `json()` is never fulfilled return Promise.reject(resp.json()); } }) .catch((error) => { // Do something with the error object }
3 回答
倚天杖
TA贡献1828条经验 获得超3个赞
// This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());
好吧,resp.json诺言将得到兑现,只是Promise.reject不等待它,而是立即兑现诺言。
我假设您宁愿执行以下操作:
fetch(url).then((resp) => {
let json = resp.json(); // there's always a body
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})
(或明确写出)
return json.then(err => {throw err;});
添加回答
举报
0/150
提交
取消