为长时间运行的任务轮询REST API

我正在devise一个REST API来执行一些需要大量计算的任务,以供其他服务使用。 实质上,GET /command GET /command将开始执行任务,状态在/queue/12345处更新。 客户端轮询/queue/12345/直到任务完成,此时服务器发送一个303结果位置( /runs/12345 )。

我现在想要做的是在客户端写轮询function。 我现在所拥有的可以成功地进行轮询 – 但是,因为setTimeout()函数在发送请求之后立即被调用。 这意味着我将永远轮询,即使我没有在请求的callback函数中调用setTimeout()

一旦我收到303状态码,我怎样才能确保我的轮询function结束?

 // standard first call is pollQueue(uri, 0); function pollQueue(uri, timesPolled, callback) { if(timesPolled > 28800) { // 288800 is (60 sec/min * 60 min/hr * 24 hr) / 3 sec/poll. Aka 24 hours. throw 'ResourceWillNeverBeReady'; } console.log("polling " + uri); request({ url: "http://localhost:2500/" + uri, followRedirect: false }, function (error, response, body) { if(response.statusCode === 303) { // callback handles requesting the actual data callback(response.headers.location); return; } }); setTimeout(function() { pollQueue(uri, timesPolled + 1, callback);}, 3000); } 

凯文B指出明显的。 我所需要做的就是将setTimeout()函数移到callback函数中。

 // standard first call is pollQueue(uri, 0); function pollQueue(uri, timesPolled, callback) { if(timesPolled > 28800) { // 288800 is (60 sec/min * 60 min/hr * 24 hr) / 3 sec/poll. Aka 24 hours. throw 'ResourceWillNeverBeReady'; } console.log("polling " + uri); request({ url: "http://localhost:2500/" + uri, followRedirect: false }, function (error, response, body) { if(response.statusCode === 303) { // callback handles requesting the actual data callback(response.headers.location); return; } setTimeout(function() { pollQueue(uri, timesPolled + 1, callback);}, 3000); }); }