繁体   English   中英

如何在 Node.js 中等待回调 function 调用?

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

我是 Node.js 和 Javascript 的新手,我使用了 npm ZEFE90A8E604A7C840E88D03A677 重试发送请求到服务器。

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在 function 传递给operation.attempt之前返回 promise。尝试解析 promise。

如何解决这个问题?

这个问题的解决方案取决于operation.attempt 如果它返回 promise 您也可以在SendReqToServer中简单地返回 promise 。 但通常带有回调的异步函数不会返回承诺。 创建您自己的 promise:

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

如果 function 中没有错误,则返回operation.attempt()将返回resp.datasendReqToServer() 目前,您只是将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;}
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM