Confused on how to chain queries using promises using .then()
The function(doSomething)
runs when the previous promise completes successfully, and doSomething
is the response. You can chain the promises using then
like:
query("SELECT * FROM books where book_id = $1")
.then(() => query("SELECT * FROM username where username = $2"))
.then(() => query("SELECT * FROM saved where saved_id = $3"));
This will execute the three SQL queries in sequence.
However, since you'll most likely want to save the response, you could use async/await
for simplicity:
async function threeQueries() {
//Fetch all three queries in sequence
let queryOne = await query("SELECT * FROM books where book_id = $1");
let queryTwo = await query("SELECT * FROM username where username = $2");
let queryThree = await query("SELECT * FROM saved where saved_id = $3");
//Extract the response text from our queries
let resultOne = await queryOne.text();
let resultTwo = await queryTwo.text();
let resultThree = await queryThree.text();
//Return the responses from the function
return [resultOne, resultTwo, resultThree];
}
You could also use Promise.all
like so:
Promise.all([
query("SELECT * FROM books where book_id = $1"),
query("SELECT * FROM username where username = $2"),
query("SELECT * FROM saved where saved_id = $3")
]);
The purpose of Promises is to enable better flow control of asynchronous operations. Use Promise.all for cases where you have multiple tasks that must complete, in any order, before code flow can proceed. Use Promise.then when you have multiple async tasks where each step may partially depend on the result of a previous (e.g. after querying your books table you query the username table using books.savedByUserId to fetch the appropriate user record).
Referencing some examples from: https://codeburst.io/node-js-mysql-and-promises-4c3be599909b The author provides a simple mySql wrapper that returns Promises (database.query returns new Promise).
//In this example Promise.all executes the queries independently, but provides an
//effective tool to resume your work after all are completed. The order in which
//they complete may be random/indeterminate.
var bookQuery = database.query( 'SELECT * FROM books where book_id = $1' );
var userQuery = database.query( 'SELECT * FROM username where username = $2' );
var saveQuery = database.query( 'SELECT * FROM saved where saved_id = $3' );
Promise.all([bookQuery,userQuery,saveQuery]).then(function(results){
//resume whatever processing that should happen afterwards
//For instance, perhaps form fields in your UI require these datasets to be loaded
//before displaying the UI.
myDialog.open()
});
// In this example, things are done sequentially, this makes the most sense
// when the result of each operation feeds into the next. Since your queries don't
// rely on each other, this is not ideally depicted.
let bookRows, userRows, savedRows ;
database.query( 'SELECT * FROM books where book_id = $1' )
.then( rows => {
bookRows = rows;
return database.query( 'SELECT * FROM username where username = $2' );
})
.then( rows => {
userRows = rows;
return database.query( 'SELECT * FROM saved where saved_id = $3' );
})
.then( rows => {
savedRows = rows;
return database.close();
})
.then( () => {
// do something with bookRows, userRows, savedRows
}
.catch( err => {
// handle the error
})
p.s. Not to muddy the waters, but in this case three sequential sql queries could likely be replaced by a single query with joins, but I guess that's not really the point of the question. Let's pretend it's three queries to separate stores, that'd make sense.