【问题标题】:How to control http request that targets Async operation如何控制以异步操作为目标的 http 请求
【发布时间】:2016-06-18 00:32:57
【问题描述】:

我正在尝试在登录过程中获取用户数据。 存储在 rethinkDb 中的数据。 流程是:

• 请求被路由到控制器(通过 express)

• 控制器选择正确的处理程序

• Handler 调用 dao.get():

  login: function (email, password, res) {
        var feedback = daouser.get(email);
        if (feedback.success) {
            var user = feedback.data;
            //Do some validatios...
        }       
        res.status = 200;
        res.send(feedback);
    },

• dao.get() 代码为:

get: function (email) {        
    var feedback = new Feedback();
    self.app.dbUsers.filter({email: email}).run().then(function (result) {
        var user = result[0];
        feedback.success = true;
        feedback.data = user;
        return feedback;
    });
}

但由于调用是通过 promise 进行的,dao.get 在实际的“Then”函数被调用之前返回并且控制器得到undefined反馈......

我的设计有问题……

【问题讨论】:

标签: node.js express promise rethinkdb


【解决方案1】:

var feedback = daouser.get(email);

您不能在此处进行同步分配,因为 .get 是异步的。另外,请注意您没有从 .get 返回任何内容,这就是它未定义的原因。 我会把这一切都变成一个承诺链。

get: function (email) {        
var feedback = new Feedback();

// RETURN is important here, this way .get() return a promise instead of undefined
return self.app.dbUsers.filter({email: email}).run().then(function (result) {
    var user = result[0];
    feedback.success = true;
    feedback.data = user;
    return feedback;
});

}

login: function (email, password, res) {
    //return the promise again, so login will be chainable too
    return daouser.get(email)
    // You can chain another then here, because you returned a promise from .get above
    // Your then function will be called with the return from the previous then, which is 'feedback'
    .then(function(feedback) {
      if (feedback.success) {
        var user = feedback.data;
        //Do some validatios...
      }       
      res.status = 200;
      res.send(feedback);
  }
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多