我正在使用Node.js,我有一个如下所示的循环:
public partial class ABSMGMT_CREW_HOURS
{
[Key]
public decimal? RID { get; set; }
[Required]
[StringLength(8)]
public string EMP_ID { get; set; }
[StringLength(50)]
public string EMP_NAME { get; set; }
[StringLength(3)]
public string PAY_CATEGORY { get; set; }
public decimal? PAY_RATE { get; set; }
[StringLength(25)]
public string PAY_CODE { get; set; }
public decimal? PAY_HOURS { get; set; }
public decimal? PAY_AMOUNT { get; set; }
[Required]
[StringLength(5)]
public string MONTH_YEAR { get; set; }
public DateTime INSERT_DATE { get; set; }
[StringLength(5)]
public string POSITION { get; set; }
}
并在运行var request = require('request');
for(var i = 0; i< some_number; i++){
console.log(i);
request( url.concat(i), function(error, response, body){
if(!error){console.log("ABC" + i)}
else{
console.log(error);
});
}
之前将0
返回some_number-1
,我不知道发生了什么。我使用的是request module。
答案 0 :(得分:1)
当你发出请求时,返回需要时间,但循环不会等待它,它会继续。这种异步性质是Javascript主要原则之一。
如果你想在继续循环之前等待每个请求,可以尝试这样的事情:
function iterator(i) {
if (i < some_number) {
request(url.concat(i), function(err, response, body) {
if (err) console.log(err);
iterator(i + 1);
});
}
}
// Kick off the loop
iterator(0);