首先,我没有异步编程经验,所以如果我错过了一些明显的东西,我很抱歉。
我经常看到这个问题出现。我知道人们不喜欢在 Javascript 中强制同步,但在这种情况下这是必要的。我正在对生产数据库进行大量调用,由于使用频率较高,该数据库无法承受太多负载。因此,我在循环中设置代码来发出请求,等待确认完成,休眠 2 秒钟,然后发出下一个请求。这是因为我每周都会在大约 10-20 分钟的时间内从该服务器提取大量数据。
这是我的代码。 Sleep 是一个使用 Date 类强制程序等待的函数。
var thread = function(cb){
cb();
};
do{
var x = thread(function(){
request.post(options, function(e, r, body){
console.log(e);
console.log(r.statusCode);
issues.push(body["issues"]);
maxResults = body["total"];
options.body.startAt += 25;
console.log("Going to sleep");
});
sleep(2000);
});
console.log("Waking up and moving to the next cycle");
}while(issues.length < maxResults);
console.log("Finished with the requests");
}
虽然我设置了回调,但我的代码仍在异步运行请求。因为我将 maxResults 保留为空,所以很明显我的回调不起作用。这是我的输出:
Waking up and moving to the next cycle
Finished with the requests
Going to sleep
最佳答案
您需要创建一个递归异步函数。
它看起来像这样:
function fetch(existingIssues) {
return sendRequest().then(function() {
existingIssues.push(...);
if (existingIssues.length >= maxResults)
return existingIssues;
else
return fetch(existingIssues);
});
}
fetch([]).then(...);
关于javascript - 尝试在 Node 中运行同步 REST 请求时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190625/