1

I have a fetch API call that calls API back end and in return, I will get the response object with status code. What I am trying to do is base on return, I wanted to return the JSON response with status code. so that other part of the javascript can manipulate base on status code. My fetch function is as follow.

I have tried with as follow below, but it returns as a given screenshot. It gives me promise value which I didn't want to get. enter image description here

export const createUser = ( posts ) => {
    const apiRoute= "/api/register";
    return window.fetch(`${apiRoute}`, {
       "headers": headers,
       method: "POST",
       body: JSON.stringify(posts)
    }).then(response => ({
        'status' : response.status,
        'data'   : response.json()
    }))
        .catch(error => console.error('Error: ', error))
        ;

}

I know that it might be the duplicate from this post (Fetch api - getting json body in both then and catch blocks for separate status codes), but I do not want my data to return as a promise. Instead, I wanted to return fully constructed well form JSON data.

Something like this.

{status: 400, data: {id:1,name:Hello World}}

how can i achieve this?

1 Answer 1

4

"It gives me promise value"

That's right, as per the documentation.

You need to resolve that promise before resolving the outer promise.

For example

.then(response => {
  return response.json().then(data => ({
    status: response.status,
    data
  }))
})

Alternatively, use an async function

export const createUser = async ( posts ) => {
  const apiRoute= "/api/register";
  try {
    const response = await window.fetch(apiRoute, {
      headers,
      method: "POST",
      body: JSON.stringify(posts)
    })
    return {
      status: response.status,
      data: await response.json()
    }
  } catch (error) {
    console.error('Error: ', error)
    throw error
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.