为什么我的函数返回一个Promise而不是我的数据库中的一个对象? [英] Why is my function returning a promise and not an object from my db?

查看:45
本文介绍了为什么我的函数返回一个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.

这篇关于为什么我的函数返回一个Promise而不是我的数据库中的一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆