Search code examples
javascriptnode.jsexpressnpm-request

Function returning undefined seems like console.log is running before result is returned? Promise needed?


I have a function in another file that I want to get the response of and then do something with that response before exiting my controller function.

Here is the code from the required file:

exports.counter = function(companyID) {
    options.json.companyID = companyID
    request.post('/monitorCounter', options, (error, response, body) => {
        if (error) {
            console.log(error);
            throw error;
        }
        if(body.success == true) return true
    });    
}

Here is how I am requiring the file/function

const monitorCounter = require('../controllers/counter').counter

Then this is how I am trying to test/use it in my main controller file

let valid = monitorCounter(companyID)
console.log(`Valid: ${valid}`)

I am expecting it to return true (tested via console.log and function works as expected), but I am getting undefined.

I was thinking that I need a promise for this but was not sure how to do it with it being a different file and I'm also not up to date fully yet on promises (working on that currently)


Solution

  • I managed to figure out how to do the promise I needed, I had tried before but was not 'return'ing a promose and was calling resolve/reject wrong. Below is working code for this issue.

    exports.counter = function(companyID) {
        return new Promise((resolve, reject) => {
            options.json.companyID = companyID
            request.post('/monitorCounter', options, (error, response, body) => {
                if (error) {
                    console.log(error);
                    throw error;
                }
                if(body.success == true) resolve(true)
                if(body.success != true) reject(false)
            });    
        });
    }