从module.exports nodeJS中的另一个函数调用函数

时间:2020-07-14 20:39:17

标签: node.js express

我想从single_view函数内部调用getData函数。在下面的代码中,getData的输出未定义返回

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){
    }
}

在singleView控制器中,路由返回未定义。我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要使用async / await。

我建议您使用axios代替请求。

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){
    }
}