我有一个带参数和回调的函数。它应该向远程API发出请求并根据参数获取一些信息。当它获得信息时,它需要将其发送到回调。现在,远程API有时无法提供。我需要我的功能继续尝试,直到它设法完成它并且然后用正确的数据调用回调。
目前,我在函数内部有以下代码,但我认为像while(!done
)这样的东西;是不正确的节点代码。
var history = {};
while (true) {
var done = false;
var retry = true;
var req = https.request(options, function(res) {
var acc = "";
res.on("data", function(msg) {
acc += msg.toString("utf-8");
});
res.on("end", function() {
done = true;
history = JSON.parse(acc);
if (history.success) {
retry = false;
}
});
});
req.end();
while (!done);
if (!retry) break;
}
callback(history);
我该怎么做正确的方法?
答案 0 :(得分:34)
没有必要重新发明轮子......在这种情况下,您可以使用流行的异步实用程序库,“重试”方法。
async.retry(3, apiMethod, function(err, result) {
// do something with the result
});
答案 1 :(得分:22)
绝对不是要走的路 - 而(!完成);将进入一个硬循环并占用你所有的cpu。
相反,你可以做这样的事情(未经测试,你可能想要实现某种退避):
function tryUntilSuccess(options, callback) {
var req = https.request(options, function(res) {
var acc = "";
res.on("data", function(msg) {
acc += msg.toString("utf-8");
});
res.on("end", function() {
var history = JSON.parse(acc); //<== Protect this if you may not get JSON back
if (history.success) {
callback(null, history);
} else {
tryUntilSuccess(options, callback);
}
});
});
req.end();
req.on('error', function(e) {
// Decide what to do here
// if error is recoverable
// tryUntilSuccess(options, callback);
// else
// callback(e);
});
}
// Use the standard callback pattern of err in first param, success in second
tryUntilSuccess(options, function(err, resp) {
// Your code here...
});
答案 2 :(得分:6)
我使用plnkr非常有用且最好的答案找到了Dmitry的答案。
这个答案将他的例子扩展为定义apiMethod函数并向其传递参数的工作版本。我打算将代码添加为注释,但单独的答案更清晰。
const async = require('async');
const apiMethod = function(uri, callback) {
try {
// Call your api here (or whatever thing you want to do) and assign to result.
const result = ...
callback(null, result);
} catch (err) {
callback(err);
}
};
const uri = 'http://www.test.com/api';
async.retry(
{ times: 5, interval: 200 },
function (callback) { return apiMethod(uri, callback) },
function(err, result) {
if (err) {
throw err; // Error still thrown after retrying N times, so rethrow.
}
});
注意,在任务中调用apiMethod(uri,callback)的替代方法是使用async.apply:
async.retry(
{times: 5, interval: 200},
async.apply(task, dir),
function(err, result) {
if (err) {
throw err; // Error still thrown after retrying N times, so rethrow.
}
});
我希望这能为某人提供一个好的复制/粘贴锅炉板解决方案。
答案 3 :(得分:5)
这是你想要做的吗?
var history = {};
function sendRequest(options, callback) {
var req = https.request(options, function (res) {
var acc = "";
res.on("data", function (msg) {
acc += msg.toString("utf-8");
});
res.on("end", function () {
history = JSON.parse(acc);
if (history.success) {
callback(history);
}
else {
sendRequest(options, callback);
}
});
});
req.end();
}
sendRequest(options, callback);
答案 4 :(得分:3)
我使用retry模块解决了这个问题。
示例:
var retry = require('retry');
// configuration
var operation = retry.operation({
retries: 2, // try 1 time and retry 2 times if needed, total = 3
minTimeout: 1 * 1000, // the number of milliseconds before starting the first retry
maxTimeout: 3 * 1000 // the maximum number of milliseconds between two retries
});
// your unreliable task
var task = function(input, callback) {
Math.random() > 0.5
? callback(null, 'ok') // success
: callback(new Error()); // error
}
// define a function that wraps our unreliable task into a fault tolerant task
function faultTolerantTask(input, callback) {
operation.attempt(function(currentAttempt) {
task(input, function(err, result) {
console.log('Current attempt: ' + currentAttempt);
if (operation.retry(err)) { // retry if needed
return;
}
callback(err ? operation.mainError() : null, result);
});
});
}
// test
faultTolerantTask('some input', function(err, result) {
console.log(err, result);
});
答案 5 :(得分:1)
您可以尝试以下几行。我正在写一个大致的想法,你应该用你的HTTP请求替换trySomething。
function keepTrying(onSuccess) {
function trySomething(onSuccess, onError) {
if (Date.now() % 7 === 0) {
process.nextTick(onSuccess);
} else {
process.nextTick(onError);
}
}
trySomething(onSuccess, function () {
console.log('Failed, retrying...');
keepTrying(onSuccess);
});
}
keepTrying(function () {
console.log('Succeeded!');
});
我希望这会有所帮助。
答案 6 :(得分:1)
名为 Flashheart 的库也是一种合适的替代方案。它是一个易于使用并支持重试的休息客户端。
例如,配置Flashheart重试10次,请求之间的延迟为500毫秒:
const client = require('flashheart').createClient({
retries: 10,
retryTimeout: 500
});
const url = "https://www.example.com/";
client.get(url, (err, body) => {
if (err) {
console.error('handle error: ', err);
return;
}
console.log(body);
});
有关详细信息,请查看文档: https://github.com/bbc/flashheart
免责声明:我为这个图书馆做出了贡献。
答案 7 :(得分:0)
不使用任何库..重试直到成功并且重试次数小于 11
let retryCount = 0;
let isDone = false;
while (!isDone && retryCount < 10) {
try {
retryCount++;
const response = await notion.pages.update(newPage);
isDone = true;
} catch (e) {
console.log("Error: ", e.message);
// condition for retrying
if (e.code === APIErrorCode.RateLimited) {
console.log(`retrying due to rate limit, retry count: ${retryCount}`);
} else {
// we don't want to retry
isDone = true;
}
}
}