爲了

2014-07-04 59 views
0

執行環路要求我具備以下條件:爲了

var request = require('request') 
var j = request.jar() 
var url1 = "www.google.com" 
var url2 = "www.google.com/images" 
request({url: url1,jar: j}, function() { 
... 
for (var i = 0; i < list.length; i++) { 
// list is just an item from a json response. 
// I need map the list[i] with the body into a JSON object. 
// But if I move the this to the request it get the last item and not each. 
console.log(list[i]) 
request({url: url2,jar: j}, function(err, response, body) { 
      // This print after all the list[i] has printed 
      body = JSON.parse(body) 
      console.log(body); 
     }); 
} 
}); 

我想JSON數組是這樣的代碼註釋

[{a: list[i], b: body}, {a: list[i], b: body}] 

問題。我不是JavaScript /節點。我可能不會理解事情的工作方式。

+0

有很多的代碼從這個摘錄失蹤。不知道在哪裏聲明瞭一些變量等。 –

+0

我增加了更多。這有幫助嗎? – CWon

回答

0

可以使用封閉以保護其在回調捕捉i值:

for (var i = 0; i < list.length; i++) 
{ 
    (function(i) { 

     request({ url: url2, jar: j }, function(err, response, body) { 
      console.log(list[i]); 
      body = JSON.parse(body); 
      console.log(body); 
     }); 

    })(i); 
} 
+0

這有幫助。如何將一切推送到一個json數組,然後將該數組放到關閉之外? – CWon