For some reason, in node.js, the code is not running in order. It is running the console.log(data2) before even retrieving the data from function2. I am assuming it is because node.js runs asynchronously. However, I am not too sure how to fix it. Thanks for all the help in advance
function function1(app){
app.post('/test', (req, res, next) => {
const url = `url1`;
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
var data2 = function2(data.id);
console.log(data2); //undefined
res.send(profileData);
}
});
})
}
function function2(id){
const url = `url2/${id}`;
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
console.log(data); //output correct data
return data;
}
});
}
function function1(app){
app.post('/test', (req, res, next) => {
const url = `url1`;
request(url, async function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
var data2 = await function2(data.id);
console.log(data2); //undefined
res.send(profileData);
}
});
})
}
function function2(id) {
const url = `url2/${id}`;
return new Promise(function (resolve, reject) {
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
resolve(JSON.parse(body));
} else {
reject(error);
}
});
});
}
Because you're calling function2() just before outputting console.log(data2). The latter gets executed immediately, while the former has to make a server request. Pass data2 to function2() instead and output it after you output the result from function2()
function function1(app){
app.post('/test', (req, res, next) => {
const url = `url1`;
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
var data2 = function2(data.id, data2);
res.send(profileData);
}
});
})
}
function function2(id, data2){
const url = `url2/${id}`;
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
console.log(data); //output correct data
console.log(data2); //undefined
return data;
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With