在NodeJS中For之后进行回调的最佳方法是什么?

时间:2015-02-22 18:30:53

标签: node.js for-loop asynchronous callback

我已经用PHP开发了很多年,现在我正在尝试学习NodeJS,而且我遇到了异步函数的问题......

我在NodeJS中有这个功能( source是一个用户数组):

//userformat.js

var age = module.exports.age = function(date){

  var diff = new Date - new Date(date);
  var diffdays = diff / 1000 / (60 * 60 * 24);
  var age = Math.floor(diffdays / 365.25);

  return age;

}

...etc.

//index.js

function format(source, me, callback){

    var len = source.length

    for (var i = 0; i < len; i++){

        source[i]['_age'] = userFormat.age(source[i]['birthday']);
        source[i]['_rating'] = userFormat.rating(source[i]['votes']);
        source[i]['_is_followed'] = userFormat.followed(source[i]['fllws'], me);

    }

    callback(null, source);

}

我知道Node中的函数是错误,因为函数可能在for()中的函数完成之前调用回调,并且数组中的值可能是未定义的,因为这个原因我使用回调改变了函数:

//userformat.js

var age = module.exports.age = function(date, callback){

      var diff = new Date - new Date(date);
      var diffdays = diff / 1000 / (60 * 60 * 24);
      var age = Math.floor(diffdays / 365.25);

      callback(age);

    }
...etc.

//index.js

function format(source, me, callback){

    var len = source.length

    for (var i = 0; i < len; i++){

        userFormat.age(source[i]['birthday'], function(resul){

            source[i]['_age'] = resul;

            userFormat.rating(source[i]['votes'], function(resul){

                source[i]['_rating'] = resul;

                userFormat.followed(source[i]['fllws'], me, function(resul){

                    source[i]['_is_followed'] = resul;

                    //Callback
                    if (i == len-1){
                        callback(null, source);
                    }

                })

            })


        })

    }

}

这是对的吗?我有另一种方式来提高效率或优雅吗?

非常感谢你!

1 个答案:

答案 0 :(得分:0)

我认为你误解了nodeJS中异步的概念。您的代码不是异步的,并且循环后将始终调用您的回调。

请检查此问题:how do i create a non-blocking asynchronous function in node.js?