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 })
    });
};
4
  • Possible duplicate of Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Commented Sep 21, 2016 at 2:14
  • Should move res.json(...) into 2nd callback, after model.sublist Commented Sep 21, 2016 at 2: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. Commented Sep 21, 2016 at 2:22
  • boo is an array, for each intem inside boo y need to execute some query based on boo item.text Commented Sep 21, 2016 at 2:32

1 Answer 1

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
       });
    });
 }
Sign up to request clarification or add additional context in comments.

1 Comment

e() is executed before sublist callback ends, so b.foo = undefined , how i can achieve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.