Why are these fetch methods asynchronous?

后端 未结 4 1879
轮回少年
轮回少年 2021-01-18 05:46

Fetch is the new Promise-based API for making network requests:

fetch(\'https://www.everythingisawesome.com/\')
  .then(response => console.log(\'status:          


        
4条回答
  •  借酒劲吻你
    2021-01-18 06:16

    Looking at the implementation here the operation of fetching json is CPU bound because the creation of the response, along with the body is done once the response promise is done. See the implementation of the json function

    That being said, I think that is mostly a design concept so you can chain your promise handlers and only use a single error handler that kicks in, no matter in what stage the error happened.

    Like this:

    fetch('https://www.everythingisawesome.com/')
      .then(function(response) {
        return response.json()
      })
      .then(function(json) {
        console.log('parsed json', json)
      })
      .catch(function(ex) {
        console.log('parsing or loading failed', ex)
      })
    

    The creation of the already resolved promises is implemented with a pretty low overhead. In the end it is not required to use a promise here, but it makes for better looking code that can be written. At least in my opinion.

提交回复
热议问题