【问题标题】:Nodejs + Express + mysql callback issueNodejs + Express + mysql 回调问题
【发布时间】:2016-09-21 02:11:29
【问题描述】:

我在理解回调的行为时遇到了一些麻烦。 例如,下面的代码不能像预期的那样工作 cos callbacks 。 我尝试了异步库,但没有获得所需的行为。

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

编辑解决方案:

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 })
    });
};

【问题讨论】:

  • 应该在model.sublist之后将res.json(...)移动到第二个回调中
  • 为什么节点框架给你一个响应对象,你可以发送消息而不是让你的函数返回一个值(框架通常在其他语言中工作的方式)正是为了让你可以获取数据异步然后发送响应。因此,只需将响应发送到正确的位置,而不是在您收到之前。
  • boo 是一个数组,对于 boo 中的每个 intem 都需要根据 boo item.text 执行一些查询

标签: node.js express callback


【解决方案1】:

应该只在第二次回调中调用响应。 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
       });
    });
 }

【讨论】:

  • e() 在子列表回调结束之前执行,所以 b.foo = undefined ,我该如何实现呢?
猜你喜欢
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多