如何等待 Node.js 中的回调函数调用?

How to await a callback function call in Node.js?

我是 Node.js 和 Javascript 的新手,我使用 npm package retry 向服务器发送请求。

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;}
        }
    });
}

我得到空响应,因为 SendReqToServer returns 函数传递给 operation.attempt 之前的承诺解决了承诺。

如何解决这个问题?

返回 operation.attempt() 将 return resp.data 如果函数 sendReqToServer() 没有错误。 目前,您只是 return 将 resp.data 转换为 operation.attempt()。您还需要 return 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;}
        }
    });
}

这道题的答案取决于operation.attempt。如果它 return 是一个承诺,您也可以简单地 return 在 SendReqToServer 中的那个承诺。但通常带有回调的异步函数不会 return 承诺。创建您自己的承诺:

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;}
            }
        });
    });
}