如何处理for循环中的回调(Node.JS)

Chi*_*g24 0 mongoose mongodb node.js

我正在尝试使用NodeJS编写代码,我从外部API中获取数据,然后使用Mongoose在MongoDB中填充它们.在这之间,我将检查Mongo中是否已存在该特定内容.以下是我的代码.

router.route('/report') // the REST api address
  .post(function(req, res) // calling a POST 
  {
    console.log('calling report API');
    var object = "report/" + reportID; // related to the API
    var parameters = '&limit=100' // related to the API
    var url = link + object + apiKey + parameters; // related to the API

    var data = "";
    https.get(url, function callback(response)
    {
      response.setEncoding("utf8");
      response.on("data", function(chunk)
      {
        data += chunk.toString() + ""; 
      });

      response.on("end", function()
      {
        var jsonData = JSON.parse(data);
        var array = jsonData['results']; // data is return in array of objects. accessing only a particular array
        var length = array.length;
        console.log(length);

        for (var i = 0; i < length; i++) 
        {
          var report = new Report(array.pop()); // Report is the schema model defined. 
          console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^');
          console.log(i);
          console.log('*****************************');
          console.log(report);
          console.log('*****************************');
          // console.log(report['id']);

          /*report.save(function(err)
          {
            if(err)
              res.send(err);
          });*/

          Report.find({id:report['id']}).count(function(err, count) // checks if the id of that specific data already exists in Mongo
          {
            console.log(count);
            console.log('*****************************');
            if (count == 0) // if the count = 0, meaning not exist, then only save
            {
              report.save(function(err)
              {
                console.log('saved');
                if(err)
                  res.send(err);
              });
            }
          });
        };
        res.json({
                    message: 'Grabbed Report'
                  }); 
      });
      response.on("error", console.error);
    });
  })
Run Code Online (Sandbox Code Playgroud)

我的问题是,由于NodeJS回调是并行的,因此不会按顺序调用它.我的最终结果是这样的:

  1. 调用报告API
  2. console.log(length)= 100
  3. ^^^^^^^^^^^^^^^^^^^^^^^^
  4. console.log(i)=从0开始
  5. *******************************
  6. console.log(report)=将存储在Mongo中的数据
  7. *******************************
  8. 数字3 - 7重复100次,因为长度等于100
  9. console.log(count)= 0或1
  10. 9号重复100次
  11. 的console.log( '拯救')
  12. 11号重复100次
  13. 最后,只有100个数据中的最后一个存储在Mongo中

我需要的是某种处理这些回调的技术或方法,这些回调是一个接一个地执行而不是顺序跟随循环.我很确定这是问题,因为我的其他REST API都在工作.

我已经研究过异步方法,承诺,递归函数以及其他一些我真正理解如何解决这个问题的方法.我真的希望有人可以对这件事情有所了解.

如果我在提出问题的方式上犯了任何错误,请随意纠正我.这是我在StackOverflow中发布的第一个问题.

lag*_*lex 5

这个问题被称为"回调地狱".还有很多其他方法,比如使用你会发现的PromiseAsync库.

我对本机asyncES7带来了更多的兴趣,你现在可以开始使用它与开发者库Babel.

但到目前为止,我发现的最简单的方法如下:你取出长回调函数并在外面定义它们.

router.route('/report') // the REST api address
    .post(calling_a_POST)

function calling_a_POST(req, res) {
    ...
    var data = "";
    https.get(url, function callback(response) {
        ...
        response.on("end", response_on_end_callback); // --> take out
        response.on("error", console.error);
    });
}

function response_on_end_callback() {                 // <-- define here
    ...
    for (var i = 0; i < length; i++) {
        var report = new Report(array.pop());
        ...
        Report.find({ id: report['id'] })
              .count(Report_find_count_callback);     // --> take out
    };
    res.json({
        message: 'Grabbed Report'
    });
}

function Report_find_count_callback(err, count) {     // <-- define here
    ...
    if (count == 0) {
        report.save(function(err) {                   // !! report is undefined here
            console.log('saved');
            if (err)
                res.send(err);                        // !! res is undefined here
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

需要注意的是,您将无法访问曾经作为回调的所有变量,因为您已将它们从范围中移除.

这可以通过各种"依赖注入"包装来解决,以传递所需的变量.

router.route('/report') // the REST api address
    .post(calling_a_POST)

function calling_a_POST(req, res) {
    ...
    var data = "";
    https.get(url, function callback(response) {
        ...
        response.on("end", function(err, data){       // take these arguments
            response_on_end(err, data, res);          // plus the needed variables
        });
        response.on("error", console.error);
    });
}

function response_on_end(err, data, res) {  // and pass them to function defined outside
    ...
    for (var i = 0; i < length; i++) {
        var report = new Report(array.pop());
        ...
        Report.find({ id: report['id'] })
            .count(function(err, count){
                Report_find_count(err, count, report, res);  // same here
            });
    };
    res.json({                                        // res is now available
        message: 'Grabbed Report'
    });
}

function Report_find_count(err, count, report, res) {        // same here
    ...
    if (count == 0) {
        report.save(function(err) {                   // report is now available
            console.log('saved');
            if (err)
                res.send(err);                        // res is now available
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

当我执行response_on_end函数时,我收到undefined:1 unexpected token u错误.我非常确定它与这一行有关:var jsonData = JSON.parse(data)response_on_end的如下:var jsonData = JSON.parse(data); // problem here

我意识到我在这里犯了错误:

function calling_a_POST(req, res) {
    ...
    var data = "";
    https.get(url, function callback(response) {
        ...
        //sponse.on("end", function(err, data){
        response.on("end", function(err){ // data shouldn't be here
            response_on_end(err, data, res);
        });
        response.on("error", console.error);
    });
}
Run Code Online (Sandbox Code Playgroud)

我可以预见的另一个问题,实际上可能不会出现在这里,但仍然会更好地谈论.的data变量,因为它是一个字符串,它是不同于对象的原语类型,它是"按值传递". 更多信息

最好将变量包装在一个对象中并传递该对象,因为javascript中的对象总是"通过引用传递".

function calling_a_POST(req, res) {
    ...
    // var data = ""; // 
    var data_wrapper = {};
    data_wrapper.data = {};                                // wrap it in an object
    https.get(url, function callback(response) {
        ...
        response.on("data", function(chunk){
            data_wrapper.data += chunk.toString() + "";   // use the dot notation to reference
        });
        response.on("end", function(err){ 
            response_on_end(err, data_wrapper, res);      // and pass that object
        });
        response.on("error", console.error);
    });
}

function response_on_end_callback(err, data_wrapper, res) {
    var data = data_wrapper.data;                         // later redefine the variable
    ...
    for (var i = 0; i < length; i++) {
        var report = new Report(array.pop());
        ...
Run Code Online (Sandbox Code Playgroud)