0

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 })
    });
};
9879800
  • 57
  • 1
  • 1
  • 7
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Felix Kling Sep 21 '16 at 02:14
  • Should move `res.json(...)` into 2nd callback, after `model.sublist` – tmquang6805 Sep 21 '16 at 02:14
  • The reason WHY node frameworks give you a response object that you can send messages on instead of having your function return a value (the way frameworks usually work in other languages) is exactly so that you can get data asynchronously and THEN send a response. So just send the response at the correct place, not before you receive it. – slebetman Sep 21 '16 at 02:22
  • boo is an array, for each intem inside boo y need to execute some query based on boo item.text – 9879800 Sep 21 '16 at 02:32

1 Answers1

2

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
       });
    });
 }
Abhilash Km
  • 116
  • 1
  • 5