0

I have a file "test.js" where I have a function that uses the 'request' module to get the response from a url. I call this function from another file, 'run.js' where I first store the return value and then print it out. I get 'undefined' as the output and I am unable to apply async/await to make it work. How can I make the console.log(res) to wait for the makeRequest() call to return a value?

test.js -

const request = require("request");

function makeRequest(url){
    request(url, (error, response, html) => {
        if(!error && response.statusCode == 200) {

            return html;

        } else { 
            console.log(error);
        }
    });
}

module.exports = makeRequest;

run.js -

const makeRequest = require("./test");

async function getResult(){
    var res = await makeRequest("https://www.google.com");
    console.log(res);
}

Rohit
  • 1,385
  • 2
  • 15
  • 21
  • `makeRequest` isn't returning anything. Return the promisified `request`, or accept a callback – CertainPerformance Feb 21 '19 at 09:40
  • 1
    wrap a `Promise` around the callback in `makeRequest` – Davin Tryon Feb 21 '19 at 09:42
  • Thanks. I found the answer in the link given above :) – Rohit Feb 21 '19 at 10:00
  • I'm unable to grab the logic behind this for some reason. I keep running into the same issue every now and then. Check out [this](https://jsfiddle.net/bunnyrabbit/1h7rqc65/) code where I'm trying to read from a table in Amazon redshift. I call it as follows - [link](https://jsfiddle.net/bunnyrabbit/kvyuLfxs/) When I use await, it awaits the function execution to store the result in `data`, but when I do console.log(data), it says `undefined`. There has to be some logic but I just cant seem to get it. Can I use async/await` without callbacks? – Rohit May 01 '19 at 05:15
  • I'm able to do it using callbacks, but I want to know if there is any way to do it just with async/await? – Rohit May 01 '19 at 05:25

0 Answers0