Thursday, 16 July 2020

NodeJS - Waiting For Function to Complete

I hope someone can assist, I am learning NodeJS/Express.js and am struggling.The code below outputs the contents of two variables, however there are times when the res.send command is initiated before the second function ('city2') has had time to complete. From what I have read online, I need to use an await command to allow the second function time to complete before the remaining code is executed.Additionally, res.write does not seem to work, as I would like to enter headings before the variable is displayed - is there anything I would need to add extra to get res.write to work?Any help is greatly appreciated - Thank you.var express = require('express'); var app = express(); const https = require('https'); var peopleDB; var peopleDB2; var cityName; app.get('/city/:query', city, (req, res) => { console.log(req.params.query); }) async function city (req, res){ cityName = req.params.query; var url = 'https://asdf-mytest-app.herokuapp.com/city/' + cityName + '/users'; const request = https.get(url, response => { let body = ""; response.on('data', data =>{ body += data.toString(); }); response.on('end', () => { const people = JSON.parse(body); JSON.stringify(people); peopleDB = people; }); }); await city2(); res.send({peopleDB, peopleDB2}); } async function city2 (req, res){ cityName = req.params.query; var url = 'https://asdf-mytest-app.herokuapp.com/city/' + cityName + '/users'; const request = https.get(url, response => { let body = ""; response.on('data', data =>{ body += data.toString(); }); response.on('end', () => { const people = JSON.parse(body); JSON.stringify(people); peopleDB2 = people; }); }); }

Submitted July 16, 2020 at 01:44PM by mgsolid2010

No comments:

Post a Comment