Skip to Content
Learn
Learn Node SQLite
Using db.each()

While learning JavaScript, you likely learned about the powerful method .forEach() that allows us to process every element in an array separately. Now we will use a similar method that will enable us to process every row returned from a database query.

db.each("SELECT * FROM Dog WHERE breed = 'Labrador'", (error, row) => { // This gets called for every row our query returns console.log(`${row.name} is a good dog`); }, (error, numberOfRows) => { // This gets called after each of our rows have been processed console.log(`There were ${numberOfRows} good dogs`); });

In the code above we SELECT all the Labrador dogs from our Dog database. We offer affirmation to each of the animals individually and then announce how many received this praise in sum.

db.each() takes a query and a callback function that it performs on each row returned from the query. This is a useful technique for transforming or updating rows. This is also useful for memory management — we only have to look at one row at a time instead of trying to process every returned row at the same time. db.each() additionally takes an optional second callback function, which will be called when all of the queries are completed and processed.

Instructions

1.

Create an empty temperaturesByYear object before your query; we’ll use this to store temperature data for each year.

2.

Inside a db.each() call, SELECT all the rows from TemperatureData.

3.

In a callback from your db.each() call, add the temperature’s value to the temperaturesByYear. To do this, use the provided helper function addClimateRowToObject(row, object). The first argument is the row to add, the second argument is the object to add it to (temperaturesByYear in your case).

4.

In the second callback to your db.each() call, create a final averageTemperatureByYear variable and set it equal to calling function calculateAverages with your temperaturesByYear object.

5.

Log these averages using the given printQueryResults() function.

Folder Icon

Sign up to start coding

Already have an account?