fetch:拒绝带有 JSON 错误对象的承诺 [英] fetch: Reject promise with JSON error object

查看:29
本文介绍了fetch:拒绝带有 JSON 错误对象的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HTTP API,它在成功和失败时都返回 JSON 数据.

I have an HTTP API that returns JSON data both on success and on failure.

失败的示例如下所示:

~ ◆ http get http://localhost:5000/api/isbn/2266202022 
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: 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 代码中实现的目标是这样的:

What I want to achieve in my JavaScript code is something like this:

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
   }

推荐答案

 // This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());

好吧,resp.json承诺实现,只有Promise.reject没有等待并立即拒绝承诺.

Well, the resp.json promise will be fulfilled, only Promise.reject doesn't wait for it and immediately rejects with a promise.

我假设您更愿意执行以下操作:

I'll assume that you rather want to do the following:

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;});

这篇关于fetch:拒绝带有 JSON 错误对象的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆