Doubt in the recovery of the value of callback in Nodejs

Asked

Viewed 41 times

0

I’m starting in Node.js running Function and would like to know how to return a db field and move to a variable, I usually use a callback, for example:

Conect.query('select nome from pessoa where id=1', function(erros, data){
Console.log(data)
}

But I would like to return in an external variable that date for example:

Var banco = Conect.query('select nome from pessoa whre id=1') 

But when I do this it returns parameters of the connection and the query being executed, I can return the value of this field in a Promisse suddenly or something like?

1 answer

0

Javascript does not work like that, all io operations (input and output) in Javascript are done asynchronously, that is, your thread does not wait for the resolution of these operations to continue running the next lines of code, then it is usually necessary to pass a callback function to be executed when io operation ends.

... Or at least that’s how it worked until 2017. Using the modifier async in your role, you can stop the execution of the function until you receive a response from a Promise. What you need to do is encapsulate this method in a Promise:

// Módulo "util" já é incluido no NodeJS
var util = require('util')
var query = util.promisify(Conect.query)

And now you can wait for that answer within a function async with the operator await:

async function minhaFuncao() {
    var data = await query('select nome from pessoa whre id=1')
}

Note that although its function awaits the resolution of the Promise, your thread does not wait. Find out how Promise, async and await work, and when it’s a good idea to use them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.