Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - determine when per-row asynchronous function is not called due to there being no rows

Tags:

node.js

sqlite

I'm trying to write code that will be executed if an SQLite query won't return results. However, the async nature of Node.js makes this difficult. I don't know if I can write code inside the callback function, because when I test with inputs that will cause empty results, nothing happens.

I'm doing

 db.each("SELECT pid, collection , photo FROM photos WHERE collection = '"+collection_id+"' AND pid = '"+photo_id+"' ", function(err, row) {
      console.log("PHOTO FOUND");

//code inside the callback function

  });
    //code I want

Specifically, I want to render something general, in case the user requests something that is not in the db What should I do?

like image 724
mariosk89 Avatar asked Nov 25 '12 17:11

mariosk89


1 Answers

This is from the API documentation for the package you appear to be using (emphasis mine):

Database#each(sql, [param, ...], [callback], [complete])

Runs the SQL query with the specified parameters and calls the callback with for each result row. The function returns the Database object to allow for function chaining. The parameters are the same as the Database#run function, with the following differences:

The signature of the callback is function(err, row) {}. If the result set succeeds but is empty, the callback is never called. In all other cases, the callback is called once for every retrieved row. The order of calls correspond exactly to the order of rows in the result set.

After all row callbacks were called, the completion callback will be called if present. The first argument is an error object, and the second argument is the number of retrieved rows. If you specify only one function, it will be treated as row callback, if you specify two, the first (== second to last) function will be the row callback, the last function will be the completion callback.

If you know that a query only returns a very limited number of rows, it might be more convenient to use Database#all to retrieve all rows at once.

So, it would seem your code should look like this:

var sql = "SELECT pid, collection , photo FROM photos WHERE collection = '"+collection_id+"' AND pid = '"+photo_id+"' ";
db.each(sql, function(err, row) {
  console.log("PHOTO FOUND");
  //code inside the callback function
}, function(err, rows) {
  if (rows == 0) {
    //code I want
  }
});
like image 136
Michelle Tilley Avatar answered Oct 25 '22 23:10

Michelle Tilley