你可以使用async.until遍歷一些邏輯,直到頭可用:
let success = true;
async.until(
// Do this as a test for each iteration
function() {
return success == true;
},
// Function to loop through
function(callback) {
request(..., function(err, response, body) {
// Header test
if(resonse.headers['Content-Disposition'] == 'attatchment;filename=...') {
response.pipe(fs.createWriteStream('./filename.zip'));
success = true;
}
// If you want to set a timeout delay
// setTimeout(function() { callback(null) }, 3000);
callback(null);
});
},
// Success!
function(err) {
// Do anything after it's done
}
)
您可以用類似的setInterval一些其他的方式做到這一點,但我會選擇異步使用友好的異步功能。
編輯:這是一個使用setTimeout
(我不喜歡用setInterval
初始延遲另一個例子
let request = require('request');
let check_loop =() => {
request('http://url-here.tld', (err, response, body) => {
// Edit line below to look for specific header and value
if(response.headers['{{HEADER_NAME_HERE}}'] == '{{EXPECTED_HEADER_VAL}}')
{
response.pipe(fs.createWriteStream('./filename.zip')); // write file to ./filename.zip
}
else
{
// Not ready yet, try again in 30s
setTimeout(check_loop, 30 * 1000);
}
});
};
check_loop();
我似乎無法得到你的答案工作,你有使用的例子。 setInterval? – MindVox
我已經用另一個例子更新了我的答案,它很快且很髒,所以你可能需要稍微調整一下。 – Ding
感謝你的回答,令人煩惱的是你的例子不起作用,因爲請求只是重複,而且會話不保持 我不確定是否需要額外的請求sts從第一。或者使用流來檢查標題,以保持連接。 – MindVox