我是Node.js和Javascript的新手,我使用npm包重试发送请求到服务器。
const retry = require('retry');
async function HandleReq() {
//Some code
return await SendReqToServer();
}
async function SendReqToServer() {
operation.attempt(async (currentAttempt) =>{
try {
let resp = await axios.post("http://localhost:5000/api/", data, options);
return resp.data;
} catch (e) {
if(operation.retry(e)) {throw e;}
}
});
}
我得到空响应,因为在传递给operation.attempt
的函数解析承诺之前,SendReqToServer
返回一个承诺。
如何解决这个问题?
这个问题的解取决于operation.attempt
。如果它返回一个承诺,您也可以简单地在SendReqToServer
中返回该承诺。但是通常带回调的异步函数不会返回承诺。创建你自己的承诺:
const retry = require('retry');
async function HandleReq() {
//Some code
return await SendReqToServer();
}
async function SendReqToServer() {
return new Promise((resolve, reject) => {
operation.attempt(async (currentAttempt) => {
try {
let resp = await axios.post("http://localhost:5000/api/", data, options);
resolve(resp.data);
return resp.data;
} catch (e) {
if(operation.retry(e)) {throw e;}
}
});
});
}
如果函数中没有错误,返回operation.attempt()
将返回resp.data
到sendReqToServer()
。目前,您只是将resp.data
返回到operation.attempt()
。您还需要返回operation.attempt()
const retry = require('retry');
async function HandleReq() {
//Some code
return SendReqToServer();
}
async function SendReqToServer() {
return operation.attempt(async (currentAttempt) => {
try {
let resp = await axios.post("http://localhost:5000/api/", data, options);
return resp.data;
} catch (e) {
if(operation.retry(e)) {throw e;}
}
});
}