0

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. Here a reproduction of the two methods I use :

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-

  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

Webwoman
  • 10,196
  • 12
  • 43
  • 87
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Roamer-1888 Aug 26 '18 at 02:09

1 Answers1

1

If you run something that returns a promise, the value can be referenced in the following parentheses e.g.

.then((data) => data)

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.

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.

sarora
  • 913
  • 9
  • 20
  • Thanks, I have found this solution : `return {ip : authModel.find({ip}).exec().then(res => res[0].ip)};` but I'm pretty sure there is more elegant solutions to make the job than my huge inline stuff – Webwoman Aug 26 '18 at 00:11