2

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)

joshk132
  • 1,011
  • 12
  • 37
  • i'm guessing that the request.post is from a library? does their docs say it is a promise or observable? it's defininitely something aysnc. so you will probably need to have something like (promise) valid.then((val) => {console.log(val)}) – andrewf Jul 02 '19 at 00:47
  • @andrewf He tagged the question with `npm-request`, that should be the library. – Barmar Jul 02 '19 at 00:50
  • @andrewf Yes it is a library used in Node.js https://www.npmjs.com/package/request – joshk132 Jul 02 '19 at 00:56
  • I don't see anything about JSON options in that documentation, or calling `request.post()` with 3 arguments. – Barmar Jul 02 '19 at 00:56
  • @Barmar That is it yes, and you can call the request exactly how I have it, been using it that way for a while. I have a good other ~60 instances in this one application that do it. See my new answer in 30 seconds to see the solutions I came up with – joshk132 Jul 02 '19 at 00:58

1 Answers1

2

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)
        });    
    });
}
joshk132
  • 1,011
  • 12
  • 37