javascriptnode.js

module.export is not exporting returned variable


I have two files, one file(intsaKey.js) i am creating a function that would create a key. Am trying to export the function using modules.export.

//instaKey.js    
const Request = require("request");

module.exports = {
instaKey: () => {

    let applicationToken;

    headers = {};
    headers["client-id"] = clientId;
    headers["client-secret"] = clientSecret;
    headers["Accept-Language"] = "en_US";
    headers["Content-Type"] = "application/json";

    Request.post({
            headers: headers,
            url: `${BaseUrl}/oauth2/token/`,
            formData: {
                grant_type: `client_credentials`,
                client_id: clientId,
                client_secret: clientSecret
            },
        },
        (error, instaApplicationTokenResponse, instaApplicationTokenResBody) => {
            if (instaApplicationTokenResponse.statusCode == 200) {
                console.log("Authentication api is success");
                applicationToken = JSON.parse(instamojoApplicationTokenResBody).access_token;
                console.log(applicationToken);
                return applicationToken;
            }
        });
},

}

In another file(payment.js), I am trying to get the key. So console.log inside instaKey.js is getting printed but the key itself is not getting printed or returned.

//payment.js
const {
instaKey
} = require("./insta");

module.exports = {

createOrder: (req, res) => {

    console.log("Key is ");
    let key = instaKey().applicationToken;
    console.log(key); //undefined :( How do I get the key here ?
    console.log(instaKey()); //
            //below gets printed 
            //Authentication api is success
            //82782ewdhjdsjchjnscnsccn
};

};

Solution

  • instaKey().applicationToken will only work if instaKey() returns an object with an applicationToken property. But your instaKey function doesn't return anything.

    Furthermore, it relies on an asynchronous Request.post completing to obtain the applicationToken. So instaKey would have to return a promise that is resolved with the value of applicationToken.

    The general pattern for the fix is to return new Promise((resolve, reject) => ... and then call resolve(applicationToken) when it's available, and of course you'll need to either await instaKey() function or use instaKey().then(key => { /* TODO: Use key here. */ }).

    Example:

    return new Promise((resolve, reject) => {
        Request.post(
            {
                headers: headers,
                url: `${BaseUrl}/oauth2/token/`,
                formData: {
                    grant_type: `client_credentials`,
                    client_id: clientId,
                    client_secret: clientSecret
                },
            },
            (error, instaApplicationTokenResponse, instaApplicationTokenResBody) => {
                if (instaApplicationTokenResponse.statusCode == 200) {
                    console.log("Authentication api is success");
                    applicationToken = JSON.parse(instamojoApplicationTokenResBody).access_token;
                    console.log(applicationToken);
                    resolve(applicationToken)
                } else {
                    console.error("Authentication api failed");
                    reject();
                }
            });
    });
    

    And then you'd have to do something like this to call it:

    createOrder: async (req, res) => {
    
        console.log("Key is ");
        let key = await instaKey();
        console.log(key);
    };