【问题标题】:How to use Promise in Sequelize Js to return a Entity如何在 Sequelize Js 中使用 Promise 返回一个实体
【发布时间】:2015-04-12 21:17:19
【问题描述】:
var user =  db.User.find({ where: { username: username }}).then(function(user) {
      console.log("Authenticate"+user.authenticate(password));
      if (!user) {
        return null;
      } else if (!user.authenticate(password)) {
          return null;
      } else {
       return user;
      }
    }).catch(function(err){
      return err;
    });

我正在将 Sequelize JS 与 Node JS 一起使用。 我想要与 where 子句匹配的用户对象。 但是当我从 then 函数返回时。但它进入无限循环。 我是 Node Js 的新手,我不知道如何在 Node Js 中使用 Promise。 请帮帮忙

【问题讨论】:

标签: javascript node.js promise sequelize.js


【解决方案1】:

尝试使用 try 和 catch 块

这是一个例子:

    authentication: async (req,res) => {

    try {

        let user = await User.findOne({
            where: {username: req.body.username}
        });

        user = user.toJSON();
        console.log(user);

       if (!user) {
               console.log('Not a user');
       }

  }

    catch (e) {

    console.log(e)

    }
}

【讨论】:

    【解决方案2】:

    db.User.find() 的返回值是一个承诺。它永远不会是用户,所以你的第一行是不正确的。

    您需要做的是从 promise then 回调中调用处理链中的下一个函数。这是 Node 中的标准做法。

    如果您从then promise 回调中返回某些内容,则假定它是另一个promise,它允许您连续链接多个promise (example)。这不是你要找的。​​p>

    你的例子会更好:

    function authentication(err, user){
      // Do something
    }
    
    db.User.find({ where: { username: username }}).then(function(user) {
          console.log("Authenticate"+user.authenticate(password));
          if (!user) {
            authentication(null, null);
          } else if (!user.authenticate(password)) {
              authentication(null, null);
          } else {
            authentication(null, user);
          }
        }).catch(function(err){
          authentication(null, user);
        });
    

    注意使用回调来表示身份验证测试的结果。还要注意 err 作为回调的第一个参数,这是标准的 Node 约定。

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2017-11-06
      • 2020-08-06
      • 1970-01-01
      相关资源
      最近更新 更多