请问在不使用nodejs中的任何第三方模块的情况下,对错误/条件进行重试的正确方法是什么?
我不确定如何在出错时调用相同的函数,以及如何将原始回调/数据传递给新调用的函数?
我需要销毁/结束套接字吗?
我尝试过寻找示例,但只找到了对第三方模块和http.get示例的引用,它们似乎不起作用。该如何测试呢?我已经尝试了以下几个步骤,但没有成功:
async pingApi(cb) {
let options = {
"method":"post",
"path": `/API/pingAPI?${this.auth}`, /ect do I reference this path?
}
};
let request = await http.request(options, (response) => {
let body = new Buffer(0);
response.on('data', (chunk) => {
body = Buffer.concat([body, chunk]);
});
response.on('end', function () {
if (this.complete) {
let decoded = new Buffer(body, 'base64').toString('utf8')
let json = JSON.parse(decoded);
if (json.result != 'OK') {
setTimeout(pingApi, 1000); //cant pass callback
} else {
cb(null, json.result) //works
}
}
});
})
request.end(); //does the socket need to be closed if retry is this function?
}
任何帮助,指出正确的方向或批评将非常感谢,因为我认为这是一个非常重要的学习曲线对我。
先谢谢你,
发布于 2018-09-04 03:27:16
您在核心节点服务器上使用async/await引起了我的兴趣,我已经尝试尽可能多地使用这种新的异步功能。
这就是我最终得到的:https://runkit.com/marzelin/pified-ping
const pify = require("util").promisify;
const http = require("http");
const hostname = "jsonplaceholder.typicode.com";
const failEndpoint = "/todos/2";
const goodEndpoint = "/todos/4";
let options = {
method: "get",
path: `${failEndpoint}`,
hostname
};
async function ping(tries = 0) {
return new Promise((res) => {
const req = http.request(options, async (response) => {
let body = new Buffer(0);
response.on("data", (chunk) => {
body = Buffer.concat([body, chunk]);
})
const on = pify(response.on.bind(response));
await on("end");
let decoded = new Buffer(body, 'base64').toString('utf8')
let json = JSON.parse(decoded);
if (json.completed) {
return res("all good");
}
if (tries < 3) {
console.log(`retrying ${tries + 1} time`);
return res(ping(tries + 1));
}
return res("failed");
})
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.end();
})
}
const status = await ping();
"status: " + status
https://stackoverflow.com/questions/52154317
复制相似问题