Reputation: 185
I am new to node and struggle hard to achieve an objective where i can return an object instance to the caller method.
Please note : object instance is getting created in a non blocking callback, and I want to pass this object back to the main module from where this has been invoked, I am able to achieve this in the same file (file b.js) but not in the main file (file a.js) using require.
example code in file b.js
var object1 = require('object1.js')
function createobject(){
object1.someFunction(err,function(myobj){
//retrun myobj to the caller function;
return myobj;
});
}
module.exports = createobject;
In a.js
var b = require('b.js');
var myobj = b.createObject();
//call some method of myobj
Please suggest experts, Thanks, Manish Bansal
Upvotes: 0
Views: 1467
Reputation: 14398
This is typical problem to someone new. You're trying to return something from async
function - which doesn't work. Use callback or promises instead:
file b.js
function createobject(next){
object1.someFunction(err,function(myobj){
//retrun myobj to the caller function;
next(myobj);
});
}
file a.js
b.createObject(function (myobj) {
// call some method of myobj
});
Upvotes: 2