简体   繁体   中英

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

I am new to Node.js and Javascript, I used npm package retry to send requests to server.

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

I get empty response because SendReqToServer returns a promise before function passed to operation.attempt resolves the promise.

How to solve this issue?

The solution to this question depends on operation.attempt . If it returns a promise you can simply return that promise in SendReqToServer , too. But usually async functions with callbacks don't return promises. Create your own 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;}
            }
        });
    });
}

Returning operation.attempt() will return resp.data if there were no errors in the function to sendReqToServer() . Currently, you're just returning the resp.data to operation.attempt() . You need to also 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;}
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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