I have a nodejs project in which a sample.js include two function
function A depends on function B's callback .
// smaple.js
Both function are included in the same file
function B ( arg1 , callback ){
// do some async
async.map(arg1 , function(item, cb){
var a = item.a
var b = a*4
cb( null , {'a':a,'b':b})
},function(err , result){
callback(err , result)
} )
}
function A ( arg , callback ){
if(condition1){
callback(null , 1)
}else{
B ( arg , function( err , result){
if(err){
callback(err , result)
}
else if (result ==1 ){
callback ( null , 2)
}else{
callback ( null , 1)
}
})
}
}
Scenario 2
// function B is in outer.js and included as module
sample.js
var outerfunction = require('./outer.js');
function A ( arg , callback ){
if(condition1){
callback(null , 1)
}else{
outerfunction.B ( arg , function( err , result){
if(err){
callback(err , result)
}
else if (result ==1 ){
callback ( null , 2)
}else{
callback ( null , 1)
}
})
}
}
outer.js
function B ( arg1 , callback ){
// do some async
async.map(arg1 , function(item, cb){
var a = item.a
var b = a*4
cb( null , {'a':a,'b':b})
},function(err , result){
callback(err , result)
} )
}
module.exports.B = B ;
Does scenario 1 is a proper way to use function ?
What will happen if this code run concurrently using cluster module?
Does scenario 2 is better way to use dependent function ?
Is this code perform better on concurrent execution?
Best Answer
Both cases will do. You just have to maintain the chain of methods to execute.
If you have one method dependent on another method, one of the way's of maintaining the chain is to call the second method inside the callback to the firs one just like you are doing I believe:
Example: