javascript - Nodejs HTTP 重试模式
问题描述
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() 并且我的函数终止。我可以请一些帮助来解决它。还试图将它包装在一个承诺周围,因为这是最佳实践。
解决方案
而不是return resolve(json);
just resolve(json);
,而不是throw reject(json);
justreject(json);
推荐阅读
- css - 列表项具有交替颜色的列表
- gitlab - 在一台服务器上以多个用户的身份运行 Gitlab-runner,用于多个项目
- authorization - 授权服务设计(应用服务)
- android - 使用选择意图从电话簿中检索保存的地址
- html - 禁止在本网站嵌入视频。观看 Odnoklassniki
- apache-camel - 仅在调用直接组件时执行路由
- css - 在 chrome 中设置 css constant() 或 env() 变量以进行调试
- laravel - 为什么 Laravel 中间件 CORS 不能与 Vue.js 一起使用
- terraform - 用于关联 Azure NSG 的 terraform 脚本的后端流程是什么
- node.js - 使用 NodeJS 的 QnAMaker 自适应卡片