使用fetch和async / await处理失败的HTTP响应

时间:2018-03-10 15:55:00

标签: javascript async-await fetch

我使用此代码通过fetch处理失败的请求(通过抛出Error):

function asyncCall() {
    fetch("https://httpstat.us/500")
    .then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response.text(); // or .json();
    })
    .then(function(text) {
        console.log("ok", text);
    }).catch(function(error) {
        console.log("error", error); 
    })

}

asyncCall();

现在我感兴趣的是这个代码的async / await版本看起来如何,这就是我带来的:

async function syncCall() {
  let response = await fetch("https://httpstat.us/200")
  if (response.ok) return await response.text()
  throw new Error(response.statusText)
}

async function callFetch() {
  try {
      let text = await syncCall()
      console.log(text)
  } catch(e) {
      console.log("error", e); 
  }
}

callFetch()

此代码是否良好,是否有更好,更短的方式?

0 个答案:

没有答案