Skip to content

Callbacks with async? #693

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
DaAwesomeP opened this issue Dec 29, 2013 · 2 comments
Closed

Callbacks with async? #693

DaAwesomeP opened this issue Dec 29, 2013 · 2 comments

Comments

@DaAwesomeP
Copy link

I am trying to run a query in an eachSeries. The problem is that doneCallback gets called before the query's callback is complete. How can I fix this?

var dataset = new Array("1","2");
var allVar1 = new Array();
async.eachSeries(dataset, function (set, doneCallback) {
    var selectallquery = 'SELECT * FROM `data' + set + '` ORDER BY id DESC LIMIT 1';
    mysqlcon.query(selectallquery, function(err, rows, fields) {
        if (err) throw err;

        allVar1.push(rows[0].var1);    // This ends up happening after or during the "Do Afterwards."

    });
    return doneCallback(null);  // Fires prematurely
}, 
function(err) {
    // Do afterwards
    console.log(allVar1);
});

Thanks!

@dougwilson
Copy link
Member

Just like any code that uses callbacks, your doneCallback neds to be within the callbck from the query method:

var dataset = new Array("1","2");
var allVar1 = new Array();
async.eachSeries(dataset, function (set, doneCallback) {
    var selectallquery = 'SELECT * FROM `data' + set + '` ORDER BY id DESC LIMIT 1';
    mysqlcon.query(selectallquery, function(err, rows, fields) {
        //if (err) throw err; // <-- Do not throw errors in callbacks
        if (err) return doneCallback(err); // <-- This is what the first argument to doneCallback is for

        allVar1.push(rows[0].var1);    // This ends up happening after or during the "Do Afterwards."

        doneCallback(null); // <-- Place here
    });
    //return doneCallback(null);  // <-- No, not here
}, 
function(err) {
    // Do afterwards
    console.log(allVar1);
});

@DaAwesomeP
Copy link
Author

Thanks! My bad.

dveeden pushed a commit to dveeden/mysql that referenced this issue Jan 31, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants