2015-02-08 136 views
1

我有一個節點應用程序,我在寫需要使用承諾異步調用。Node.js承諾使用Q

我目前有一個foreach循環從一個.then(函數())的promise中調用,但是當我返回foreach的最終結果時,我什麼也得不到。

在foreach中,我可以console.log數據的值並檢索它,但不在返回之前的for循環之外?

var Feeds = function(){ 
    this.reddit = new Reddit(); 
} 

Feeds.prototype.parseRedditData = function(){ 
    var _this  = this; 

    this.getData(this.reddit.endpoint).then(function(data){ 
     return _this.reddit.parseData(data, q); 
    }); 
} 

Feeds.prototype.getData = function(endpoint){ 
    var deferred = q.defer(); 

    https.get(endpoint, function(res) { 
     var body = ''; 

     res.on('data', function(chunk) { 
      body += chunk; 
     }); 

     res.on('end', function() { 
      deferred.resolve(JSON.parse(body)); 
     }); 
    }).on('error', function(e) { 
     deferred.reject(e); 
    }); 

    return deferred.promise; 
} 

var Reddit = function(){ 
    this.endpoint = "https://www.reddit.com/r/programming/hot.json?limit=10"; 
} 

Reddit.prototype.parseData = function(json, q){ 
    var dataLength = json.data.children.length, 
     data  = []; 

    for(var i = 0; i <= dataLength; i++){ 
     var post = {}; 

     post.url = json.data.children[i].data.url; 
     post.title = json.data.children[i].data.title; 
     post.score = json.data.children[i].data.score; 

     data.push(post); 
    } 


    return data; 
} 
+0

我沒有看到用Q的'.then'功能或'的任何地方forEach'在代碼中? – laggingreflex 2015-02-09 00:08:45

+0

問:您在調用Node.js時是否使用了「--harmony」標誌?問:你是否有任何錯誤處理程序(或任何類型的錯誤檢查)? – FoggyDay 2015-02-09 00:09:47

+0

'this.getData'在哪裏? – 2015-02-09 00:30:04

回答

-1
Feeds.prototype.parseRedditData = function(){ 
    var _this  = this; 

    this.getData(this.reddit.endpoint).then(function(data){ 
     return _this.reddit.parseData(data, q); 
    }); 
} 

,當我看到這一點,我看到承諾回調「返回」 ......我不知道你爲什麼這樣做,但我只是想確定:

我想要這個「返回」是函數'parseRedditData'的返回值,這是行不通的。

回到這裏你的數據的唯一方法是用回調或承諾,像這樣:

Feeds.prototype.parseRedditData = function(callack){ 
    var _this  = this; 

    this.getData(this.reddit.endpoint).then(function(data){ 
     callback(_this.reddit.parseData(data, q)); 
    }); 
}