So using a list of ids, I'm trying to get data for each element in the database and add that element to a list. At the end, I'm displaying it on an HTML page. How would I do that? Right now, since it executes the queries async, the list will be empty after running the code to execute the query and add the result to a list.
-
1Promise.all is probably what you're looking for?jcaron– jcaron2016-08-26 01:32:24 +00:00Commented Aug 26, 2016 at 1:32
-
Can you give us a better sense of what your code looks like including any frameworks you are using and how you're interfacing with your database?Nate Vaughan– Nate Vaughan2016-08-26 01:56:42 +00:00Commented Aug 26, 2016 at 1:56
Add a comment
|
1 Answer
Lets assume you have a table called teams that contains a row for each team, with columns like id, games, total_points, wins, and losses.
Lets assume you have an array of team id. You want to query the database for those records, then do some things with them before returning them to the front end as json.
This is how i understand your problem. If this isn't the case, please clarify in a comment on this answer.
Possible solution: Do it all in one query. I'm going to use my favorite mysql library, knexjs.
var columns = ['id', 'games', 'total_points', 'wins', 'loses'];
function getTeams(ids){
return knex.select(columns).where('id', 'in', ids)
.then((teams) => {
//do whatever with array of teams
return teams;
}
}
It's pretty much as simple as that.
1 Comment
Nicholas Harris
I actually ended up doing that when I figured out I could do more then one WHERE statement. Thanks!