Why does .json() return a promise?

后端 未结 4 2071
小鲜肉
小鲜肉 2020-11-22 04:24

I\'ve been messing around with the fetch() api recently, and noticed something which was a bit quirky.

let url = \"http://jsonplaceholder.typic         


        
4条回答
  •  猫巷女王i
    2020-11-22 04:54

    In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:

    function callApi(url) {
      return fetch(url)
        .then(response => {
          if (response.ok) {
            return response.json().then(response => ({ response }));
          }
    
          return response.json().then(error => ({ error }));
        })
      ;
    }
    
    let url = 'http://jsonplaceholder.typicode.com/posts/6';
    
    const { response, error } = callApi(url);
    if (response) {
      // handle json decoded response
    } else {
      // handle json decoded 500 series response
    }
    

提交回复
热议问题