ChikChak
ChikChak

Reputation: 1034

NodeJS router using another function that calls request does not wait for an answer

I have some route:

router.get('/test', async function (req, res, next) {
    let someValue = await someFunction();
    console.log(someValue);
}

And a function which does a GET request for some other service:

async function someFunction() {
let options = {
    url: `someURL`,
    method: 'GET',
};
request(options, async function (error, response, body) {
    if (error) {
        throw error;
    } else {
        return body['someSpecificValue'];
    }
});

}

and yet, it seems that in my router, someValue is always printed as undefined.

What am I doing wrong? how do I need to wait properly for the answer from someURL?

Upvotes: 0

Views: 155

Answers (2)

O'Dane Brissett
O'Dane Brissett

Reputation: 1283

You can use node-fetch module, which is asynchronous, instead the request

npm i node-fetch

Here's an example

const fetch = require("node-fetch");
const url = "https://jsonplaceholder.typicode.com/posts/1";
const getData = async url => {
  try {
    const response = await fetch(url);
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  }
};
getData(url);

Upvotes: 2

Rahul Sharma
Rahul Sharma

Reputation: 10111

because someFunction is not returning promise update like below or use request-promise.

function someFunction() {
    let options = {
        url: `someURL`,
        method: 'GET',
    };
    return new Promise((res, rej) => {
        request(options, function (error, response, body) {
            if (error) {
                return res(error);
            }
            return rej(body['someSpecificValue']);
        });
    });
}

OR

var rp = require('request-promise');

function someFunction() {
    let options = {
        url: `someURL`,
        method: 'GET',
    };
    return rp(options);
}

Upvotes: 1

Related Questions