我试图从 API 获取 json 响应,当我执行该调用时,我必须传递用户 ID,该用户 ID 是我从第一个请求中获取的,然后作为参数传递给第二个请求。
问题是事物运行的顺序,这是我不明白的。 谁能给我解释一下这个概念吗? 为什么我的第一个 api 请求没有发生在
之前
console.log("we got the id:"+id)
代码:
app.get('/users/:name/info', function (req, res) {
var info= [];
var id;
var name = req.params.name;
console.log("now here: "+name); //that the first console.log I get
//request to get user id
var parametros = {search_string:name};
axo.Users.get(parametros, function(error, response){
var user;
console.log("should be here next"); //that is the third
for(let i = 0; i < response.data.length ; i++)
{
user = response.data;
console.log("id"+user[i].id);
//that is the fourth console.log
id = user[i].id;
}
});
//request to get user id
//request to get user information
console.log("we got the id:"+id);
//this returns undefined /second console.log
var params = {assigned_to_id:id};
axo.Features.get(params, function(error, response){
for(let i = 0; i < response.data.length; i++)
{
info = response.data;
}
res.contentType('application/json');
res.send(JSON.stringify(info));
});
//res.sendFile(path.join(__dirname + ("/index4-prototype.html")));
});
最佳答案
这些函数在 Node.js 中异步执行,因此一个函数的执行不会等待另一个函数。
如果您需要一个接一个地运行,您可以按照您需要的顺序嵌套函数,外部函数在内部函数之前执行。
或者
您可以使用异步等待
关于node.js - Node.js中代码的执行顺序是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48925292/