The conn.query
operation is asynchronous - the call returns immediately, and the x and y values 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 completed. Note that you need to declare the variables x
and y
in a scope that encompasses all calls (for example, in the callback function of the login). If you declare, as you had in your original code, the variables in the callback of query
, they will not be accessible out of 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
}
}
});