2013-12-14 118 views
0

我是Nodejs和異步編程的新手。我在執行異步函數中的GET請求時遇到問題。在這裏,我發佈了整個代碼。我試圖拉取所有Url的列表,將它們添加到列表中並將列表發送給另一個函數。NodeJS無法異步發出GET請求

我的問題是處理它們。 Inturn每個url我正在執行一個GET請求來獲取主體並在其中查找圖像元素。我正在尋找將圖像url作爲GET參數傳遞給第三方api。我無法執行GET請求,因爲控件似乎根本沒有到達那裏。

var async = require("async"), 
request = require("request"), 
cheerio = require("cheerio"); 


async.waterfall([ 

function(callback) { 
    var url = "someSourceUrl"; 
    var linkList = []; 
    request(url, function(err, resp, body) { 
     var $ = cheerio.load(body); 
     $('.list_more li').each(function() { 
      //Find all urls and add them to a list 
      $(this).find('a').each(function() { 
       linkList.push($(this).attr('href')); 
      }); 
     }); 
     callback(null, linkList); 
    }); 
}, 


//pass all the links as a list to callback 
function(liksListFetched, callback) { 
    for (var i in liksListFetched) { 
     callback(null, liksListFetched[i]); 
    } 
}], 

//***********My problem is with the below code************** 
function(err, curUrl) { 
    var cuResp = ""; 
    console.log("Currently Processing Url : " + curUrl); 

    request(curUrl, function(err, resp, body) { 

     var $ = cheerio.load(body); 
     var article = $("article"); 
     var articleImage = article.find("figure").children('img').attr('src'); 
     var responseGrabbed = "API response : "; 
     //check if there is an IMG element 
     if (articleImage === undefined) { 
      console.log("No Image Found."); 
      articleImage = 'none'; 
     } 
     else { 
      //if there is an img element, pass this image url to an API, 
      //So do a GET call by passing imageUrl to the API as a GET param 
      request("http://apiurl.tld?imageurl=" + articleImage, function(error, response, resp) {    //code doesn't seem to reach here 
       I would like to grab the response and concatenate it to the responseGrabbed var. 
       console.log(resp); 
       responseGrabbed += resp; 
      }); 
     } 
     console.log(responseGrabbed);// api response never gets concatenated :(
     console.log("_=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=_"); 
     process.exit(0); 
    }); 
}); 

我很感激,如果有人能幫助我理解根本原因。提前致謝。

回答

3

request()是異步的,所以當你登錄控制檯的字符串,字符串尚未建成的是,你所要做的回調內部控制檯日誌:

request("http://apiurl.tld?imageurl=" + articleImage, function(error, response, resp) {        
    responseGrabbed += resp; 
    console.log(responseGrabbed);// api response never gets concatenated :(
    console.log("_=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=_"); 
}); 

同去的終止過程,這應該完成所有請求完成時

+0

嗨快速問題,在這種情況下,不應該console.log(收穫)記錄響應?對不起如果我缺少一些東西。 –

+0

@EswarRajeshPinapala - 它應該,如果你沒有得到迴應,你必須控制檯登錄錯誤參數,看看有什麼告訴你。 – adeneo

+0

我的不好,我在問題中發佈了很多東西,所以當我對原始腳本進行更改時,我搞砸了。現在我明白了這個問題,以及爲什麼它的工作。萬分感謝。 –