简体   繁体   English

GraphQL解析器-承诺解决后返回我的函数

[英]GraphQL resolver - returns my function after promise resolved

I'm making a request to server to fetch some values and push them in an array 我正在向服务器发出请求以获取一些值并将其推入数组中

My GraphQL server's return me the array before the process ending, hence returns an empty array. 我的GraphQL服务器在处理结束之前向我返回了数组,因此返回了一个空数组。 Here a reproduction of the two methods I use : 这里是我使用的两种方法的复制:

1- 1-

  var array= [];
        var auths= authModel.find({}).exec()
        .then(res => {

            res.map(el =>{ 
                array.push(el.ip)
            })
        }).then(() => array)

console.log(auths) // object Promise
console.log(array) // []

2- 2-

  const auths= authModel.find().exec();
            if(!auths){ 
                throw new Error("Error while fetching users...")
            }
            console.log("auths:", auths) //  Promise { <pending> }
            return auths // on graphiql > "auths": { "ip": null }

What is going wrong ? 怎么了? How make my element returns when the promise is resolved ? 兑现承诺后,如何使我的元素返回?

Any hint would be great, thanks 任何提示都很好,谢谢

If you run something that returns a promise, the value can be referenced in the following parentheses eg 如果您运行返回承诺的内容,则可以在以下括号中引用该值,例如

.then((data) => data) .then((数据)=>数据)

Will return the data obtained from the promise. 将返回从诺言获得的数据。

If you want to do something locally with the returned data, like assign it to a local variable, you can do that within the then. 如果您想对返回的数据进行本地处理,例如将其分配给本地变量,则可以在then内进行。

Alternately if you just need to return the data to the parent function that invoked this resolver function, then just add a return statement to the beginning of the authmodel.find statement as well. 或者,如果您只需要将数据返回给调用此解析程序功能的父函数,则只需在authmodel.find语句的开头也添加一个return语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM