Realizing two queries in SalesForce generates Undefined values

2

I'm running two queries in SalesForce. However, when I try to use the values received outside the scope of the query, they are undefined. Here is the code:

var conn = new jsforce.Connection();
conn.login('email', 'password', function(err, res) {

    if (err) { 
        return console.error(err); 
    }

    conn.query('consulta', function(err, isWon) {
        if (err) {
            return console.error(err); 
        }
        var x = isWon;
        console.log(x); // Funciona aqui
    });

    conn.query('consulta', function(err, oppNum) {
        if (err) {
            return console.error(err); 
        }
        var y = oppNum;
        console.log(y); //Funciona aqui
    });

    console.log(x, y); // NÃO FUNCIONA AQUI
});
    
asked by anonymous 10.05.2016 / 18:58

1 answer

2

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
        }
    }
});
    
10.05.2016 / 19:02