函数外的空数组

时间:2016-03-14 13:32:48

标签: node.js express

在函数外接收一个空数组?

var triggerImageQuery = function(start, length,callback) {
  var feedData = [];
  var feedInfo = result.rows[start];
  var imgQuery = pgFormat("select * from feedImages where feedId=%L",feedInfo.feedid);
    model.client.query(imgQuery,function(err,result){
        if(result.rows.length > 0){
            var imgArr =[];
            for(var j=0;j<result.rows.length;j++){
                    var image = "http://"+config.host+":"+config.port+"/"+result.rows[j].imageurl;
                        imgArr.push(image);
            }
            feedData.push(feedInfo);
            feedData.push(imgArr);
        }
        else{
            feedData.push(feedInfo);
        }
console.log(feedData) // prints data correctly
    });
console.log(feedData) // here data gets empty?
    if(start < length) {
        start++;
        triggerImageQuery(start, length-1);
    }
    callback(feedData); // unable to callback here because of empty array`
}
triggerImageQuery(0, result.rows.length,function(result){
    res.json(result); // `result is empty`
});

即使我尝试过声明var feedData = [];在顶部,但没有用。

并且还尝试了model.client.query中的回调,但是有类似TypeError的错误:回调不是函数。

1 个答案:

答案 0 :(得分:0)

只需要在client.query方法中返回数据。

var triggerImageQuery = function (start, length, callback) {
    var feedData = [];
    var feedInfo = result.rows[start];
    var imgQuery = pgFormat("select * from feedImages where feedId=%L", feedInfo.feedid);
    model.client.query(imgQuery, function (err, result) {
        if (result.rows.length > 0) {
            var imgArr = [];
            for (var j = 0; j < result.rows.length; j++) {
                var image = "http://" + config.host + ":" + config.port + "/" + result.rows[j].imageurl;
                imgArr.push(image);
            }
            feedData.push(feedInfo);
            feedData.push(imgArr);
        }
        else {
            feedData.push(feedInfo);
        }
        console.log(feedData) // here data gets empty?
        if (start < length) {
            start++;
            triggerImageQuery(start, length - 1);
        }
        callback(feedData);
    });
}
triggerImageQuery(0, result.rows.length, function (result) {
    res.json(result); // `result is empty`
});