Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused on how to chain queries using promises using .then()

I just can't seem to wrap my head around chaining queries with promises. What's confusing me the most is the .then(function(doSomething) part.

What am I supposed to put in the function(doSomething)? And what does it do?

Could someone chain these queries for me without using Promise.all but instead using .then()? So I can learn from this

SELECT * FROM books where book_id = $1

SELECT * FROM username where username = $2

SELECT * FROM saved where saved_id = $3
like image 652
WHOATEMYNOODLES Avatar asked Jun 14 '19 23:06

WHOATEMYNOODLES


People also ask

What are the methods for chaining promises?

JavaScript Promise Chaining You can perform an operation after a promise is resolved using methods then() , catch() and finally() .

How do you resolve a Promise then?

The Promise.resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What does then () return?

The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .

How do you handle multiple promises?

In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.


2 Answers

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")
]);
like image 183
Jack Bashford Avatar answered Sep 20 '22 02:09

Jack Bashford


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.

like image 45
Dave Avatar answered Sep 19 '22 02:09

Dave