简体   繁体   中英

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

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 (eg 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
    })

ps 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.

We use promises which are objects that may produce a single value some time in the future.

As you run query("query string") , it will return a Promise object asynchronously. Meaning, your app is not going to wait for the query to finish. It is going to start the query process and move on to the next line of code.

So, how do we handle the query when it is done?

We use then to process the information that the query returns. then will get triggered when the query successfully completed its process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM