Search code examples
javascriptnode.jspromisees6-promise

How to embed a promise in a node.js module?


I have tried to embed a promise in node.js module but I can't return the value in result and the second promise code block is ran before the promise in the module. However, it should be the opposite. The code after the "then should ran after the promise in the NodeJs module. Also, I was forced to use global variables and I know it is not a good approach.

auth4.js

module.exports = 
    new Promise ((resolve,error)=>{

    setTimeout(function(){ 
        ok = "should appear last too"; 
        console.log("called in module and should be first", 
        JSON.stringify(credentials));
    }, 10000);

    resolve(ok);
    error(ok);
});

main.js

global.ok = "";
global.credentials = {username:'jojo',password:'test123'};
require('./auth4.js').then(function(result){
    console.log("should be displayed last",result);
});

Solution

  • I would think you are looking for

    // auth4.js
    module.exports = function(credentials) {
        return new Promise((resolve, error) => {
            setTimeout(() => {
                console.log("called in module and should be first", JSON.stringify(credentials));
                resolve("should appear last too");
            }, 10000);
        });
    };
    

    // main.js
    require('./auth4.js')({username:'jojo',password:'test123'}).then(function(ok) {
        console.log("should be displayed last", ok);
    });