Return fetch .json inside object.

前端 未结 3 1786
旧时难觅i
旧时难觅i 2020-12-12 07:22

I have an API calling function that I would like to return the response.json() content as well as the response.status together in a single object.

Like so:

3条回答
  •  一生所求
    2020-12-12 07:37

    Use async/await. That will make things much cleaner:

    async function getData(endpoint) {
      const res = await fetch(endpoint, {
        method: 'GET'
      })
    
      const body = await res.json()
    
      return {
        status: res.status,
        body
      }
    }
    

    You also might want to add a try / catch block and a res.ok check to handle any request errors or non 20x responses.

提交回复
热议问题