Why does .json() return a promise?

后端 未结 4 1992
小鲜肉
小鲜肉 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条回答
  •  臣服心动
    2020-11-22 05:00

    This difference is due to the behavior of Promises more than fetch() specifically.

    When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.

    The 2nd snippet could also have been written as:

    iterator.then(response =>
        response.json().then(post => document.write(post.title))
    );
    

    In both this form and yours, the value of post is provided by the Promise returned from response.json().


    When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:

    iterator.then(response =>
        Promise.resolve({
          data: response.json(),
          status: response.status
        })
        .then(post => document.write(post.data))
    );
    

    post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.

提交回复
热议问题