0

I want to call the function getData from inside the single_view function. in the below code the output of getData is return as undefined

var request = require("request");

module.exports = {
    getData: (url) => {
        request(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                return {success: false, data: JSON.parse(body)};
            }
            else{
                return {success: false, data: "API call failed"};
            }
        });
    },
    singleView: (req, res) => {
        var post_url = "http://example.in/wp-json/wp/v2/posts?slug="+req.params.postSlug;
        var post_api_data = module.exports.getData(post_url);
        if(post_api_data['success'] == true && post_api_data['data'].length > 0){
    }
}

In the singleView controller, the route returns undefined. How do I fix this?

Saeesh Tendulkar
  • 638
  • 12
  • 30
  • Possible duplicate: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323 – Take-Some-Bytes Jul 14 '20 at 20:52

1 Answers1

0

You need to use async/await.

I would recommend you to use axios instead of request.

const axios = require("axios");

module.exports = {
    getData: async (url) => {
        let result = await axios({url: url, method: 'GET'});
        return result.data;
    },
    singleView: (req, res) => {
        var post_url = "http://tmccms.ajency.in/wp-json/wp/v2/posts?slug="+req.params.postSlug;
        var post_api_data = await module.exports.getData(post_url);
        if (post_api_data['success'] == true && post_api_data['data'].length > 0){
    }
}
Daniel Barral
  • 3,896
  • 2
  • 35
  • 47