Why does the this Node.js request call always return undefined?

Question:
Why does this request API call always return undefined, but can console log just fine within the call? Could it be a timing issue, and if so, how can I solve this issue?

const request = require('request');
testUrl = 'https://opentdb.com/api.php?amount=1';

const callApi = (url, e) => {
    request(testUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(JSON.parse(body));
        }
        return JSON.parse(body);
    });
}

let apiData = callApi();
console.log(apiData);

I will continue looking into it, but request is deprecated, and is probably out of date: request - npm. You should probably switch to a non deprecated package.

2 Likes

You are not actually returning anything. Inside of callApi you also call into request and one of the parameters is a callback function. Inside the callback function you are returning the value, but it does not return to the top level where you want it. Instead you should do something like this where you set a value to the body and then return that.

const request = require('request');
testUrl = 'https://opentdb.com/api.php?amount=1';

const callApi = (url, e) => {
    let data;
    request(testUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(JSON.parse(body));
        }
        data = JSON.parse(body);
    });
    return data;
}

let apiData = callApi();
console.log(apiData);

Also as @dragonhunter1 said, this package is deprecated and you might want to switch to another one.

2 Likes

Oh goodness :man_facepalming:

I had e in there to do that but blanked out. I blame my lack of sleep.