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
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
Share
Improve this question
edited Jun 14, 2019 at 23:49
Jack Bashford
44.2k11 gold badges55 silver badges82 bronze badges
asked Jun 14, 2019 at 23:40
WHOATEMYNOODLESWHOATEMYNOODLES
89712 silver badges27 bronze badges
3
- Do you have a promise-returning function for executing these queries already? Do you use a specific database library? – Bergi Commented Jun 15, 2019 at 9:00
-
Do you already have working code that uses
Promise.all
? – Bergi Commented Jun 15, 2019 at 9:00 -
What do you want to put in the
then
callback? Do you know how callbacks work in general? Have you read the documentation of thethen
method? – Bergi Commented Jun 15, 2019 at 9:01
3 Answers
Reset to default 5The function(doSomething)
runs when the previous promise pletes 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 plete, 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 pleted. The order in which
//they plete 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.
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 pleted its process.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744366538a4570731.html
评论列表(0条)