由于某种原因,在node.js中,代码未按顺序运行。它甚至在从function2检索数据之前正在运行console.log(data2)。 我假设这是因为node.js异步运行。但是,我不太确定如何解决它。 感谢您提前提供的所有帮助
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;
}
});
}
答案 0 :(得分:2)
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);
}
});
});
}
答案 1 :(得分:0)
因为您正要在输出function2()
之前调用console.log(data2)
。后者立即执行,而前者必须发出服务器请求。将data2
传递给function2()
并在从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;
}
});
}