Reputation: 57
I 'm having some trouble understanding the behavior of callbacks . For example, the following code does not work as expected cos callbacks . I tried async library but without obtaining the desired behavior.
module.exports.list = function ( req, res ) {
model.list( id, idx, function( boo ){
async.forEachOf( boo, function ( b, k, e ) {
model.sublist( b.text, function( foo ) {
b.foo = foo;
})
})
res.json({ data : boo }) //boo dont have foo porperty
});
};
model.list = execute some big mysql query, and return rows (boo is an array).
model.sublist = same as model.list
Edit Solution:
module.exports.list = function ( req, res ) {
model.list( id, idx, function( boo ){
async.forEachOf( boo, function ( b, k, e ) {
model.sublist( b.text, function( foo ) {
b.foo = foo;
e();
})
})
res.json({ data : boo })
});
};
Upvotes: 0
Views: 158
Reputation: 116
should call response only in 2nd callback. read async documentation
module.exports.list = function ( req, res ) {
model.list( id, idx, function( boo ){
async.forEachOf( boo, function ( b, k, e ) {
model.sublist( b.text, function( foo ) {
b.foo = foo;
});
e();
},function(){
res.json({ data : boo }) //boo dont have foo porperty
});
});
}
Upvotes: 2