0

I'm making a call to my db, and want to use the results to fire off a request to another server, and then handle the responses. I want to do this asynchronously so I am trying to use the async library.

var sendRequest = function (store) {

    console.log(store);
}

connection.connect();

connection.query('SELECT * from stores', function(err, rows, fields) {
    if (!err){
        async.each(rows, function(row, sendRequest) {
            var store = {id: row.id, address: row.address};
            //console.log(store); <-- this works
            sendRequest(store); <-- this logs {id: '', address: null} only once
        }, function(err){
            console.log(err);
        });
    }
    else
        console.log('Error performing query');
});

connection.end();

If I log the store variable directly, it logs for each instance in the array rows and properly. If I try to do it through the sendRequest callback, it does it only once and improperly.

5
  • Can you tell me if you are using the nodeJS "async" library here? npmjs.com/package/async#each Commented Apr 29, 2015 at 2:10
  • @NormanBreau, yes I am. Thats the async.each function call. Commented Apr 29, 2015 at 2:11
  • It's probably a bad idea to have two variables named sendRequest. It can cause potential confusion making people think the sendRequest inside the async.each callback have anything to do with the sendRequest function at the top. Commented Apr 29, 2015 at 2:16
  • @slebetman, but I want it to call that function. Commented Apr 29, 2015 at 2:19
  • 1
    @haaduken: Ha! see! even you are confused! Then rename the other variable (the function argument) to something else to stop it from being overridden. Commented Apr 29, 2015 at 2:21

1 Answer 1

2

You confused some things. You're using the same name, sendRequest, for the each callback. You should do instead:

connection.query('SELECT * from stores', function(err, rows, fields) {
  if (!err){
    async.each(rows, function(row, callback) {
        var store = {id: row.id, address: row.address};
        sendRequest(store);
        callback();

    }, function(err){
        console.log(err);
    });
  }
  else
    console.log('Error performing query');
});
Sign up to request clarification or add additional context in comments.

3 Comments

so what goes in callback and where is it defined?
@haaduken: That callback is passed to you by async.each, just like row
callback is an argument of the function that async.each has to call for each item in the array, to notify that it has finished. You can use whatever name you want, just make sure that this name is not in use by other functions or variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.