Node express multiple queries in one route that depend on each other The Next CEO of Stack OverflowHow to include route handlers in multiple files in Express?How to get all registered routes in Express?How do I update each dependency in package.json to the latest version?Proper way to return JSON using node or ExpressNode emitters with expressHow do Express and hapi compare to each other?Sending HTML5 geolocation results back to Node/Express ServerExpress req.body not WorkingSails How to redirect page when bad request/400 error occurs?Passport-local times out on create user (Node, Express, Postgres, Knex)

"misplaced omit" error when >centering columns

Which one is the true statement?

Why is my new battery behaving weirdly?

Is it professional to write unrelated content in an almost-empty email?

Rotate a column

Why don't programming languages automatically manage the synchronous/asynchronous problem?

No sign flipping while figuring out the emf of voltaic cell?

How to count occurrences of text in a file?

How to avoid supervisors with prejudiced views?

is it ok to reduce charging current for li ion 18650 battery?

Do I need to write [sic] when a number is less than 10 but isn't written out?

Why did CATV standarize in 75 ohms and everyone else in 50?

Why isn't acceleration always zero whenever velocity is zero, such as the moment a ball bounces off a wall?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Why didn't Khan get resurrected in the Genesis Explosion?

Unclear about dynamic binding

Would be okay to drive on this tire?

Axiom Schema vs Axiom

How to scale a tikZ image which is within a figure environment

Why this way of making earth uninhabitable in Interstellar?

Is it possible to replace duplicates of a character with one character using tr

Running a General Election and the European Elections together

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Why do remote US companies require working in the US?



Node express multiple queries in one route that depend on each other



The Next CEO of Stack OverflowHow to include route handlers in multiple files in Express?How to get all registered routes in Express?How do I update each dependency in package.json to the latest version?Proper way to return JSON using node or ExpressNode emitters with expressHow do Express and hapi compare to each other?Sending HTML5 geolocation results back to Node/Express ServerExpress req.body not WorkingSails How to redirect page when bad request/400 error occurs?Passport-local times out on create user (Node, Express, Postgres, Knex)










0















I am just about getting familiar with node and express and programming in general, but this is a more complex issue I am trying to solve. Please if you can provide with some best practice in this kind of scenario.



I am trying to run two queries to my database where the first one is dependent on the result of the first. Q1. Return a list of ids. Q2. Return id and coord for each of the ids. I want to respond with a json object that look something like this



[
id: 451, coords: 'POINT(12.5574 43.8351)' ,
id: 56, coords: 'POINT(13.5574 44.8351)'
]


Currently I cannot get it to work, I know there is probably several issues with my example code, but I have pretty much got stuck. Maybe I am overthinking this and make it harder than it is, or bad practice in general.
How can I run multiple queries where the second use the output from the first one and then build the correct object to respond with. Any pointers would be much appreciated.



router.get('/asset/:id', (req, res) => 
let latLngOfAssets = []
// get associated assets
function getConnectionsById()
queries.getConnectionsById(req.params.id) // return list of objects
.then(data =>
if (data)
data.forEach(function(element)
getLatLngofAsset(element.til_poi_id) // for each id in list call function to get coordinate
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)


function getLatLngofAsset(id)
queries.getPoilatlng(id) // Return geometry as text for asset with id
.then(data =>
let newassetobj =
if (data)
newassetobj["id"] = data.rows[0].id
newassetobj["coords"] = data.rows[0].st_astext
//console.log(newassetobj) // structure of each object id: 451, coords: 'POINT(12.5574 43.8351)'
latLngOfAssets.push(newassetobj) // making list of objects i want to respond with
else
throw new Error('Did not get any poi');

)


getConnectionsById()

.catch(err => // message: "Cannot read property 'then' of undefined", error: …
console.error('Something went wrong', err);
);
);









share|improve this question






















  • This is callback hell getting worse by defining nested functions and choosing function name same as of member function name

    – Soulimane Mammar
    Mar 7 at 16:59











  • Use aggregate and $lookup to write cleaner queries

    – Soulimane Mammar
    Mar 7 at 17:08











  • Thanks I will look into more of the details of what you are suggesting

    – geogrow
    Mar 7 at 18:52















0















I am just about getting familiar with node and express and programming in general, but this is a more complex issue I am trying to solve. Please if you can provide with some best practice in this kind of scenario.



I am trying to run two queries to my database where the first one is dependent on the result of the first. Q1. Return a list of ids. Q2. Return id and coord for each of the ids. I want to respond with a json object that look something like this



[
id: 451, coords: 'POINT(12.5574 43.8351)' ,
id: 56, coords: 'POINT(13.5574 44.8351)'
]


Currently I cannot get it to work, I know there is probably several issues with my example code, but I have pretty much got stuck. Maybe I am overthinking this and make it harder than it is, or bad practice in general.
How can I run multiple queries where the second use the output from the first one and then build the correct object to respond with. Any pointers would be much appreciated.



router.get('/asset/:id', (req, res) => 
let latLngOfAssets = []
// get associated assets
function getConnectionsById()
queries.getConnectionsById(req.params.id) // return list of objects
.then(data =>
if (data)
data.forEach(function(element)
getLatLngofAsset(element.til_poi_id) // for each id in list call function to get coordinate
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)


function getLatLngofAsset(id)
queries.getPoilatlng(id) // Return geometry as text for asset with id
.then(data =>
let newassetobj =
if (data)
newassetobj["id"] = data.rows[0].id
newassetobj["coords"] = data.rows[0].st_astext
//console.log(newassetobj) // structure of each object id: 451, coords: 'POINT(12.5574 43.8351)'
latLngOfAssets.push(newassetobj) // making list of objects i want to respond with
else
throw new Error('Did not get any poi');

)


getConnectionsById()

.catch(err => // message: "Cannot read property 'then' of undefined", error: …
console.error('Something went wrong', err);
);
);









share|improve this question






















  • This is callback hell getting worse by defining nested functions and choosing function name same as of member function name

    – Soulimane Mammar
    Mar 7 at 16:59











  • Use aggregate and $lookup to write cleaner queries

    – Soulimane Mammar
    Mar 7 at 17:08











  • Thanks I will look into more of the details of what you are suggesting

    – geogrow
    Mar 7 at 18:52













0












0








0








I am just about getting familiar with node and express and programming in general, but this is a more complex issue I am trying to solve. Please if you can provide with some best practice in this kind of scenario.



I am trying to run two queries to my database where the first one is dependent on the result of the first. Q1. Return a list of ids. Q2. Return id and coord for each of the ids. I want to respond with a json object that look something like this



[
id: 451, coords: 'POINT(12.5574 43.8351)' ,
id: 56, coords: 'POINT(13.5574 44.8351)'
]


Currently I cannot get it to work, I know there is probably several issues with my example code, but I have pretty much got stuck. Maybe I am overthinking this and make it harder than it is, or bad practice in general.
How can I run multiple queries where the second use the output from the first one and then build the correct object to respond with. Any pointers would be much appreciated.



router.get('/asset/:id', (req, res) => 
let latLngOfAssets = []
// get associated assets
function getConnectionsById()
queries.getConnectionsById(req.params.id) // return list of objects
.then(data =>
if (data)
data.forEach(function(element)
getLatLngofAsset(element.til_poi_id) // for each id in list call function to get coordinate
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)


function getLatLngofAsset(id)
queries.getPoilatlng(id) // Return geometry as text for asset with id
.then(data =>
let newassetobj =
if (data)
newassetobj["id"] = data.rows[0].id
newassetobj["coords"] = data.rows[0].st_astext
//console.log(newassetobj) // structure of each object id: 451, coords: 'POINT(12.5574 43.8351)'
latLngOfAssets.push(newassetobj) // making list of objects i want to respond with
else
throw new Error('Did not get any poi');

)


getConnectionsById()

.catch(err => // message: "Cannot read property 'then' of undefined", error: …
console.error('Something went wrong', err);
);
);









share|improve this question














I am just about getting familiar with node and express and programming in general, but this is a more complex issue I am trying to solve. Please if you can provide with some best practice in this kind of scenario.



I am trying to run two queries to my database where the first one is dependent on the result of the first. Q1. Return a list of ids. Q2. Return id and coord for each of the ids. I want to respond with a json object that look something like this



[
id: 451, coords: 'POINT(12.5574 43.8351)' ,
id: 56, coords: 'POINT(13.5574 44.8351)'
]


Currently I cannot get it to work, I know there is probably several issues with my example code, but I have pretty much got stuck. Maybe I am overthinking this and make it harder than it is, or bad practice in general.
How can I run multiple queries where the second use the output from the first one and then build the correct object to respond with. Any pointers would be much appreciated.



router.get('/asset/:id', (req, res) => 
let latLngOfAssets = []
// get associated assets
function getConnectionsById()
queries.getConnectionsById(req.params.id) // return list of objects
.then(data =>
if (data)
data.forEach(function(element)
getLatLngofAsset(element.til_poi_id) // for each id in list call function to get coordinate
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)


function getLatLngofAsset(id)
queries.getPoilatlng(id) // Return geometry as text for asset with id
.then(data =>
let newassetobj =
if (data)
newassetobj["id"] = data.rows[0].id
newassetobj["coords"] = data.rows[0].st_astext
//console.log(newassetobj) // structure of each object id: 451, coords: 'POINT(12.5574 43.8351)'
latLngOfAssets.push(newassetobj) // making list of objects i want to respond with
else
throw new Error('Did not get any poi');

)


getConnectionsById()

.catch(err => // message: "Cannot read property 'then' of undefined", error: …
console.error('Something went wrong', err);
);
);






node.js express






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 16:44









geogrowgeogrow

189212




189212












  • This is callback hell getting worse by defining nested functions and choosing function name same as of member function name

    – Soulimane Mammar
    Mar 7 at 16:59











  • Use aggregate and $lookup to write cleaner queries

    – Soulimane Mammar
    Mar 7 at 17:08











  • Thanks I will look into more of the details of what you are suggesting

    – geogrow
    Mar 7 at 18:52

















  • This is callback hell getting worse by defining nested functions and choosing function name same as of member function name

    – Soulimane Mammar
    Mar 7 at 16:59











  • Use aggregate and $lookup to write cleaner queries

    – Soulimane Mammar
    Mar 7 at 17:08











  • Thanks I will look into more of the details of what you are suggesting

    – geogrow
    Mar 7 at 18:52
















This is callback hell getting worse by defining nested functions and choosing function name same as of member function name

– Soulimane Mammar
Mar 7 at 16:59





This is callback hell getting worse by defining nested functions and choosing function name same as of member function name

– Soulimane Mammar
Mar 7 at 16:59













Use aggregate and $lookup to write cleaner queries

– Soulimane Mammar
Mar 7 at 17:08





Use aggregate and $lookup to write cleaner queries

– Soulimane Mammar
Mar 7 at 17:08













Thanks I will look into more of the details of what you are suggesting

– geogrow
Mar 7 at 18:52





Thanks I will look into more of the details of what you are suggesting

– geogrow
Mar 7 at 18:52












1 Answer
1






active

oldest

votes


















0














You've done a good job separating out the two distinct sections of your code into separate functions - what you're missing is the ability to tie them together. This portion of your code is not doing what I think you are trying to accomplish:



data.forEach(function(element) 
getLatLngofAsset(element.til_poi_id)
);


Because getLatLngofAsset() is Promise-based* you need to use it like a Promise. You first need to make getLatLngofAsset return the Promise chain it creates. Then, it can be await-ed inside getConnectionsById using an async function:



 function getConnectionsById() 
queries.getConnectionsById(req.params.id)
.then(data =>
if (data)
data.forEach(async function(element) // <-- note the async keyword here
await getLatLngofAsset(element.til_poi_id)
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)



This is a start - there are a couple more things we can tackle once you understand the relationship between the functions you have declared and the Promises they create & return.






share|improve this answer























  • Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

    – geogrow
    Mar 7 at 18:51











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55048894%2fnode-express-multiple-queries-in-one-route-that-depend-on-each-other%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You've done a good job separating out the two distinct sections of your code into separate functions - what you're missing is the ability to tie them together. This portion of your code is not doing what I think you are trying to accomplish:



data.forEach(function(element) 
getLatLngofAsset(element.til_poi_id)
);


Because getLatLngofAsset() is Promise-based* you need to use it like a Promise. You first need to make getLatLngofAsset return the Promise chain it creates. Then, it can be await-ed inside getConnectionsById using an async function:



 function getConnectionsById() 
queries.getConnectionsById(req.params.id)
.then(data =>
if (data)
data.forEach(async function(element) // <-- note the async keyword here
await getLatLngofAsset(element.til_poi_id)
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)



This is a start - there are a couple more things we can tackle once you understand the relationship between the functions you have declared and the Promises they create & return.






share|improve this answer























  • Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

    – geogrow
    Mar 7 at 18:51















0














You've done a good job separating out the two distinct sections of your code into separate functions - what you're missing is the ability to tie them together. This portion of your code is not doing what I think you are trying to accomplish:



data.forEach(function(element) 
getLatLngofAsset(element.til_poi_id)
);


Because getLatLngofAsset() is Promise-based* you need to use it like a Promise. You first need to make getLatLngofAsset return the Promise chain it creates. Then, it can be await-ed inside getConnectionsById using an async function:



 function getConnectionsById() 
queries.getConnectionsById(req.params.id)
.then(data =>
if (data)
data.forEach(async function(element) // <-- note the async keyword here
await getLatLngofAsset(element.til_poi_id)
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)



This is a start - there are a couple more things we can tackle once you understand the relationship between the functions you have declared and the Promises they create & return.






share|improve this answer























  • Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

    – geogrow
    Mar 7 at 18:51













0












0








0







You've done a good job separating out the two distinct sections of your code into separate functions - what you're missing is the ability to tie them together. This portion of your code is not doing what I think you are trying to accomplish:



data.forEach(function(element) 
getLatLngofAsset(element.til_poi_id)
);


Because getLatLngofAsset() is Promise-based* you need to use it like a Promise. You first need to make getLatLngofAsset return the Promise chain it creates. Then, it can be await-ed inside getConnectionsById using an async function:



 function getConnectionsById() 
queries.getConnectionsById(req.params.id)
.then(data =>
if (data)
data.forEach(async function(element) // <-- note the async keyword here
await getLatLngofAsset(element.til_poi_id)
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)



This is a start - there are a couple more things we can tackle once you understand the relationship between the functions you have declared and the Promises they create & return.






share|improve this answer













You've done a good job separating out the two distinct sections of your code into separate functions - what you're missing is the ability to tie them together. This portion of your code is not doing what I think you are trying to accomplish:



data.forEach(function(element) 
getLatLngofAsset(element.til_poi_id)
);


Because getLatLngofAsset() is Promise-based* you need to use it like a Promise. You first need to make getLatLngofAsset return the Promise chain it creates. Then, it can be await-ed inside getConnectionsById using an async function:



 function getConnectionsById() 
queries.getConnectionsById(req.params.id)
.then(data =>
if (data)
data.forEach(async function(element) // <-- note the async keyword here
await getLatLngofAsset(element.til_poi_id)
);
else
throw new Error('No data returned');

console.log(latLngOfAssets) // What I want to respond with res.json(latlngofassets)
)



This is a start - there are a couple more things we can tackle once you understand the relationship between the functions you have declared and the Promises they create & return.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 7 at 17:02









jakemingollajakemingolla

63749




63749












  • Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

    – geogrow
    Mar 7 at 18:51

















  • Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

    – geogrow
    Mar 7 at 18:51
















Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

– geogrow
Mar 7 at 18:51





Thanks for your answer, not sure if I follow completely. The getLatLngofAsset() is calling the query in its body which is a promise (given from using knex js). It seem to be building the newassetobj for each id correctly. But it is for some reason not pushing it to the latLngOfAssets list, it is empty when I log it. I would however not be surprised if there is something i dont see. I am not sure where I in the code should return the response with res.json(data) I did try and just add the "await" as in your reply, but it gives me "SyntaxError: Unexpected identifier"

– geogrow
Mar 7 at 18:51



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55048894%2fnode-express-multiple-queries-in-one-route-that-depend-on-each-other%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович