node.js - Node.js中代码的执行顺序是什么

标签 node.js api

我试图从 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/

相关文章:

javascript - Node : res. 发送数组不起作用

php - 禁止获取 twitch channel 源

api - 在 Google Analytics(分析)用户事件报告 API 中,JSON 响应中 1 的采样大小是什么意思?

api - Twitter 是否对其 OAuth API 使用任何类型的权限?

ios - x-www-form-urlencoded objective-c

node.js - 套接字.io : how to control & check the message flow?

javascript - 上传到 S3 返回 Forbidden

javascript - 我应该重新编写游戏服务器、编写转发器还是使用新插件?

javascript - Mongoose findByIdAndUpdate 方法来切换和更新数据库中的 bool 值

java - SOAP:如何在 Java 中调用 CountryInfoService WSDL 文件,例如使用 CapitalCity SOAP 操作