woutergoku
woutergoku

Reputation: 45

How to wait for an async to finish - NodeJs

I am using an async to do a second database query. The result of that query, must be added as an object to the first query.

The problem is that when the async is finished, the data hasn't changed, because he already sends the unchanged data. Is there a way to wait for the async to finish?

I have used a timeout, but the size of the data is unknown, so that isn't a good solution.

The code so far:

connection.query('SELECT * FROM SENSORS', function(err,rows) {
   if(rows.length !== 0) {
    DEBUG_WRITE('sensor/','GET',200);
    async.eachSeries(rows, function(row, callback) {
     connection.query('SELECT * FROM LOCATIONS WHERE LocationID=?',row.LocationID, function (error, result) {
        row.location = result; 
            callback(null,rows);
        });
    });
    res.status(200);
    res.send(rows);
   } else {
       DEBUG_WRITE('sensor','GET',404);
       res.status(404);
       res.send({status: "No entries found"});
   }
});

Upvotes: 1

Views: 521

Answers (1)

Alex
Alex

Reputation: 38529

eachSeries takes a function that basically is a "I'm finished" function:

connection.query('SELECT * FROM SENSORS', function(err,rows) {
   if(rows.length !== 0) {
    DEBUG_WRITE('sensor/','GET',200);

    async.eachSeries(rows, function(row, callback) {
     connection.query('SELECT * FROM LOCATIONS WHERE LocationID=?',row.LocationID, function (error, result) {
        row.location = result; 
            callback(null,rows);
        });
    }, function(err){ //treat this as "i'm done iterating"

       // if any of the iterations produced an error, err will equal that error
      if(err) {
        //do something with the error
        res.status(500);
        return res.send(err);
      }

      res.status(200);
      return res.send(rows);
    });
   } else {
       DEBUG_WRITE('sensor','GET',404);
       res.status(404);
       res.send({status: "No entries found"});
   }
});

See here - it's the same as each so the function is the same

Upvotes: 1

Related Questions