Ajay Sabarish
Ajay Sabarish

Reputation: 71

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 ?

Upvotes: 1

Views: 3860

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16454

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

Upvotes: 3

codeR developR
codeR developR

Reputation: 497

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

Upvotes: 0

Related Questions