The operation conn.query
is asynchronous - the call returns immediately, and the values of x and y have not yet been assigned when you print them. You need to wait for the operation to complete (when the function you pass as parameter is called) to be able to use the values of x and y:
var conn = new jsforce.Connection();
conn.login('email', 'password', function(err, res) {
if (err) {
console.error(err);
}
conn.query('consulta', function(err, isWon) {
if (err) {
console.error(err);
return;
}
var x = isWon;
console.log(x); // Funciona aqui
conn.query('consulta', function(err, oppNum) {
if (err) {
console.error(err);
return;
}
var y = oppNum;
console.log(x, y); // Aqui você pode usar os valores de x e y
});
});
});
You can also run the two queries "in parallel", and use a counter to check when all queries have been completed. Note that you need to declare variables x
and y
in a scope encompassing all calls (for example, in the callback login). If you declare, as you had in your original code, the variables in the callback of query
, they will not be accessible outside this context.
var conn = new jsforce.Connection();
conn.login('email', 'password', function(err, res) {
if (err) {
console.error(err);
}
var numeroDeConsultas = 2;
var consultasTerminadas = 0;
var x, y;
conn.query('consulta', function(err, isWon) {
if (err) {
console.error(err);
return;
}
x = isWon;
verificaTerminadas();
}
conn.query('consulta', function(err, oppNum) {
if (err) {
console.error(err);
return;
}
y = oppNum;
verificaTerminadas();
});
function verificaTerminadas() {
consultasTerminadas++;
if (consultasTerminadas == numeroDeConsultas) {
console.log(x, y); // Todas as consultas foram executadas
}
}
});
Is there any way you don’t have to put one query inside the other ?
– Jonathan
Yes - I added this option in the reply.
– carlosfigueira
Yeah, it worked, I just had to modify a few things.
consulta1done = true
was not used and the variablesnumeroDeConsultas, consultasTerminadas
had to be declared globally.– Jonathan