techie20
techie20

Reputation: 508

How to send result after executing all queries

I've got following code

var data=[];
var i = 0,
    j = 9;

async.whilst(function () {
    return i <= j;
}, function (next) {
    connection.query('select * from table', function (err,rows, field) {
        data.push(rows.length);
        console.log(data);
    });

    i++;

    next();
}, function (err) {
    console.log(data);
});

I want to execute the query first and then return result. How should I do it. I've also done it with simple for loop but does not work.

Upvotes: 0

Views: 430

Answers (2)

Chris&#39;
Chris&#39;

Reputation: 14513

Here is another simple solution with async/await if you use babeljs:

(async function() {
    let data = [];
    let i = 0;
    const j = 9;

    while (i <= j) {
        let length = await new Promise((resolve, reject) => {
            connection.query('select * from table', function(err, rows, field) {
                if (err) return reject(err);
                resolve(rows.length);
            });
        });

        data.push(length);
    }

    return data;
})()

Upvotes: 0

Chris&#39;
Chris&#39;

Reputation: 14513

I think you just need to call next() after getting the result of the query:

var data = [];
var i = 0;
var j = 9;

async.whilst(
    function () { return i <= j; },
    function (next) {
        i++;

        connection.query('select * from table', function(err, rows, field) {
            data.push(rows.length);
            console.log(data);
            next();
        });
    },
    function (err) {
        console.log(data);
    }
);

Upvotes: 1

Related Questions