求nodejs大神帮我解决单线程异步问题

90后爱国 发布于 2014/07/07 16:36
阅读 319
收藏 0
exports.getDiaryAudioAndMessage = function(req, res){
    req.body.starId = "yangyang";
    req.body.timeArray = [{startDate:"2014-04-04T08:13:29.788Z",endDate:"2014-05-03T08:13:29.788Z"}
    ,{startDate:"2014-07-04T08:13:29.788Z",endDate:"2014-08-03T08:13:29.788Z"} 
    ];
    
    if(req.body.starId === undefined || req.body.timeArray === undefined){
        return res.json(400,{'err':'wrong request format'});
    }
    var result = {};
    for(var item in req.body.timeArray){
    Audio.getAudioByStarId(req.body.starId, req.body.timeArray[item], function(err,audioArray){
            if(err){
                return res.json(400, err);
            }
            Message.getMessageByStarId(req.body.starId, req.body.timeArray[item], function(err,messageArray){
                if(err){
                    return res.json(400,err);
                }
            var result = {};
            result['audioArray'] = audioArray;
            result['messageArray'] = messageArray;
            return res.json(200,result);   
        });
    });
    }         
}

    我想从数据库中取数据当timeArray是一组值得时候没有问题,但当 timeArray里有多组值时。返回结果与我想的不相符怎么解决???

希望能给我详细解释一下。非常感谢!!!!!!!!!


加载中
0
Arrowing
Arrowing
var result = {};

for(var item in req.body.timeArray){

	Audio.getAudioByStarId(req.body.starId, req.body.timeArray[item], function(err,audioArray){

			if(err){
					return res.json(400, err);
			}

			Message.getMessageByStarId(req.body.starId, req.body.timeArray[item], function(err,messageArray){

					if(err){
							return res.json(400,err);
					}

					var result = {};
					result['audioArray'] = audioArray;
					result['messageArray'] = messageArray;
					return res.json(200,result);   

			});
	});
}

换成,大概就是这个思路,我没环境,没做测试:

var async = require('async');
var result = [];

var handleData = function(data, callback){

	Audio.getAudioByStarId(req.body.starId, data, function(err,audioArray){

				if(err){
						return res.json(400, err);
				}

				Message.getMessageByStarId(req.body.starId, data, function(err,messageArray){

						if(err){
								return res.json(400,err);
						}

						result.push({
							audioArray: audioArray,
              messageArray: messageArray
						});

						callback();

				});
		});

}

var q = async.queue(handleData, Infinity);

q.push(req.body.timeArray);

q.drain = function() {
   res.json(200, result);
}




0
Arrowing
Arrowing
数组异步问题请参考step、async等工作控制流模块。。。
返回顶部
顶部