Skip to content

Instantly share code, notes, and snippets.

@cwatsonc
Last active November 21, 2018 21:41
Show Gist options
  • Save cwatsonc/c611896d0290b9e77696a31d08d25e68 to your computer and use it in GitHub Desktop.
Save cwatsonc/c611896d0290b9e77696a31d08d25e68 to your computer and use it in GitHub Desktop.
Asynchronous Loading of a Module Nodejs CommonJS
"use strict";
const myObject = require("./my_module.js");
console.log('*****inside invocation*****');
console.log(`myObject is of type: ${typeof myObject}`);
console.log(`myObject.log is of type`, typeof myObject.log);
const p = myObject.log();
console.log(`the value of p is currently: ${p}`);
p.then(result => {
console.log(result);
});
"use strict";
console.log('*****inside module*****');
const myObject = {};
const test = function () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("RESOLVED!");
//reject('REJECTED!');
}, 2000);
});
};
async function log() {
const result = await test();
return result;
};
console.log('typeof log: ', typeof log);
console.log('typeof myObject', typeof myObject)
myObject.log = log;
console.log('typeof myObject.log: ', typeof myObject.log);
module.exports.myObject = myObject;
console.log('typeof exports.myObject.log: ', typeof exports.myObject.log);
console.log('typeof exports.myObject', typeof exports.myObject)
'use strict';
const myObject = function () {};
const test = function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('RESOLVED!');
//reject('REJECTED!');
}, 2000);
});
};
myObject.prototype.log = async function () {
const result = await test();
return result;
};
module.exports = new myObject();
test-export-promises > node client.js
*****inside module*****
typeof log: function
typeof myObject object
typeof myObject.log: function
typeof exports.myObject.log: function
typeof exports.myObject object
*****inside invocation*****
myObject is of type: object
myObject.log is of type undefined
/Users/cwatsonx/projects/test-export-promises/client.js:7
const p = myObject.log();
^
TypeError: myObject.log is not a function
at Object.<anonymous> (/Users/cwatsonx/projects/test-export-promises/client.js:7:20)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:236:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)
test-export-promises >
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment