JS新手来了! 我正在尝试使用内置的 https lib 的请求方法来实现重试逻辑(我必须执行 POST)。还在 Azure Functions 中实现它。
编辑 我修改了代码,它会重试 HTTP 错误,但不会重试套接字或连接错误。 Doc也就是说,如果出现套接字错误,首先会调用 on('socket'),然后调用 on('error')。但当出现 ECONNRESET 或 ETIMEDOUT 错误时,我的应用程序永远不会重试。
async function fetchWithRetry(options, reqBody,context) {
return new Promise((resolve, reject) => {
let attempts = 1;
const fetch_retry = (options, n) => {
let httpsReq = httpsClient.request(options, function (res) {
const code = res.statusCode;
const message = res.statusMessage;
if (n === 0) {
reject({
'status': code,
'message': message
});
} else if (code < 200 || code >= 300) {
context.log("Retry again: Got back code: " + code + " message: " + message);
context.log("With delay " + attempts * delay);
setTimeout(() => {
attempts++;
fetch_retry(options, n - 1);
}, attempts * delay);
} else if (code === 201) {
resolve({
'status': code,
'message': message
});
} else {
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end', function () {
resolve(JSON.parse(body));
});
}
httpsReq.on('error', function (error) {
context.log("Retry again: Got back code: " + code + " message: " + message + " error: " + error);
context.log("With delay " + attempts * delay);
setTimeout(() => {
attempts++;
fetch_retry(options, n - 1);
}, attempts * delay);
});
});
httpsReq.write(reqBody);
httpsReq.end();
};
return fetch_retry(options, numberOfRetries);
});
}
当发生错误时,代码调用 end() 并且我的函数终止。我可以寻求一些帮助来修复它吗?还尝试将其包装在 promise 中,因为这是最佳实践。
最佳答案
用resolve(json);
代替returnresolve(json);
,只用resolve(json);
代替throwreject(json);
拒绝(json);
关于javascript - Nodejs HTTP 重试模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61119403/