为什么我的函数返回一个Promise而不是我的数据库中的一个对象?

为什么我的函数返回一个Promise而不是我的数据库中的一个对象?

问题描述:

我有以下两个以下功能,试图从已设置的快速服务器端点从mongo数据库中获取数据.这段代码在我的React前端应用程序中.

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;
}

以及随后的调用

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

当我登录 body 时,这是一个承诺.我期待从数据库中获取文档的json数组.我的getContacts()应该返回一个Promise,然后我在initialState中的回调从中获取数据.

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.

data.json()调用实际上是按设计返回的Promise.在文档页面此处中查看有关原因的解释.

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.

您可以通过链接另一个 then 调用或将函数声明为 async 并使用 await 来解决此问题.

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