Why would I need two callback functions in a db.each() query?

Question

Why would I need two callback functions in a db.each() query?

Answer

The reason db.each has the option of having two callback functions is that as a difference from db.get() and db.all(), db.each() runs the first callback for each result, and the second callback will be called once all the results have run through the first one. thus you can use the second callback to console log when it is done, or return a accumulated value created by the first callback.

1 Like

So, this is my version that passed.

const db = require('./db');

let totalPrice = 0;
db.each(
  'SELECT price FROM Clothing WHERE item = "shirt"',
  (err, row) => {
    if(err) {
      console.log(err)
    } else {
      totalPrice += row.price;
    }
  },
  (err, numRows) =>{
  console.log(totalPrice);
  }
);

Now, I understand that it’s a handy think to have callback that gets executed after all loops are done, but could you explain what is the role of ‘numRows’ argument in this particular exercise(code challenge 5)? Thanks.

I think I can help on this,
if we refer to this code from Lesson 8:

  (error, numberOfRows) => {
    // This gets called after each of our rows have been processed
    console.log(`There were ${numberOfRows} good dogs`);

We can see that the second value in the second callback counts the number of rows that were processed through our initial query. In our Challenge, we do not end up using it, but I imagine we could do this:

  (error, numRows) => {
    console.log(`There were ${numRows} t-shirts found, for a total of ${totalPrice}.`);

Which would be more informative and help us know how many items were calculated in the total price. Hope this helps! :slight_smile:

1 Like