我正在用node.js构建一个推特机器人游戏。我有一个脚本,它有一个同步函数(打开Twitter stream的streamOn),然后还有一个async.waterfall,它有一个HTTP GET request函数(getImage)。当脚本被触发时,getImage有时会返回301响应。streamOn继续保持打开状态,但是播放器并不知道这个错误,只是没有返回任何图像。
如果async.waterfall抛出错误,播放器仍然得到图像,我如何让它从其步骤的开始“重试”?
这是async.waterfall
streamOn(function(tweet) {
async.waterfall([
getName,
searchImage,
getImage,
postTweet.bind(null, tweet)
],
function(error, result) {
if (error) {
console.error(error);
return;
}
console.log(result);
});
}下面是getImage函数的简化版本:
function getImage() {
var http=require('http'), imageBuffer;
http.get(
'http://www.kame.net/img/kame-anime-small.gif',
function(res) {
var body=new Buffer(0);
if (res.statusCode!==200) {
return console.error('HTTP '+res.statusCode);
}
res.on('data', function(chunk) {
body=Buffer.concat([body, chunk]);
});
res.on('end', function() {
imageBuffer=body;
});
res.on('error', function(err) {
console.error(err);
});
}
);
}发布于 2016-05-23 03:39:22
这就是我想象的样子。我将调用添加到回调,因为async需要继续。
请注意,您可能会陷入重定向循环,并且我不确定.headers是否是响应的正确属性。
function getImage(url, callback) {
var http=require('http'), imageBuffer;
http.get(
url,
function(res) {
var body=new Buffer(0);
if (res.statusCode!==200) {
if (res.statusCode === 301) {
getImage(res.headers["Location"], callback) //I'm not sure if .headers is correct
return;
}
console.error('HTTP '+res.statusCode);
callback(new Error('HTTP '+res.statusCode)) //Might want a better error
}
res.on('data', function(chunk) {
body=Buffer.concat([body, chunk]);
});
res.on('end', function() {
imageBuffer=body;
callback(null, imageBuffer)
});
res.on('error', function(err) {
console.error(err);
callback(err);
});
}
);
}https://stackoverflow.com/questions/37378500
复制相似问题