如何在函数外部访问Promise回调值? [英] How do I access promise callback value outside of the function?

查看:151
本文介绍了如何在函数外部访问Promise回调值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,回调函数是异步的,不能像常规函数一样返回值.在阅读了诺言之后,我认为我对它们有了很好的理解,它们基本上是回调的增强版本,可以返回诸如异步函数之类的值.在我的 getConnections 方法中,我试图通过mongoose调用数据库上的 find()函数,并且试图获取该对象数组并将其发送给意见.

It is to my understanding that callback functions are asynchronous and cannot return a value like regular functions. Upon reading about promises, I thought I grasped a good understanding about them, that they are basically an enhanced version of callbacks that allows returning a value like asynchronous function. In my getConnections method, I am attempting to call the find() function on my database through mongoose, and I am attempting to grab this array of objects and send it to the views.

var test =  new Promise((resolve, reject) => {
        Database.find().then(list => {
            resolve(list);

        }).catch(err=> {
            return reject(err);
        })

        })
console.log(test)

当我尝试登录到Promise函数之外的控制台时,我得到 Promise {_U:0,_V:0,_W:null,_X:null}

When I attempt to log to the console outside of the promise function, I get Promise { _U: 0, _V: 0, _W: null, _X: null }

我认为这无法正常运行,并且我认为我正确地使用了Promise.任何人都可以向我指出如何在回调函数之外返回此对象数组的正确方向吗?

I don't think this is functioning correctly, and I thought I utilized promises correctly. Could anyone point me in the right direction on how to return this array of objects outside of the callback function?

推荐答案

您可以在Promise声明之前简单地添加 await .即

You can simply add await before the promise declaration. i.e.

var test = await new Promise...

这篇关于如何在函数外部访问Promise回调值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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