Why is my function returning a promise and not an

2019-08-17 18:49发布

问题:

I have the following below 2 functions attempting to get data out of a mongo database from an express server endpoint I have set up. This code is in my React front-end app.

export function getContacts() {
  let data = fetch('/api/contacts').then((data) => {
    return data.json();
  }).catch(err => console.log(err));

  return data;
}

and the following that calls it

const initialState = getContacts()
  .then((body) => {
    console.log('body: ');
    console.log(body);
    return body;
  }).catch(err => console.log(err));

when I log body it is a promise. I was expecting a json array of documents from the db. My getContacts() is supposed to return a promise and then my callback in initialState gets the data from it.

回答1:

The data.json() call is actually returning a promise by design. Take a look at the documentation page here for an explanation as to why.

You can fix it by chaining another then call or by declaring your function as async and using await.



回答2:

The .json() method is returning you a promise because the response you receive on calling api is in stages, in this case the headers are being returned in response, hence the response.json() is fired and you receive a promise for getting the body, as yet you haven't received the body but just the headers.

For fetching the body you need to chain a promise like below

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