promise - 使用 Sequelize findOne 方法在 Bluebird promise 中进行并发调用。返回未定义

标签 promise sequelize.js bluebird

我想验证来自多个表的特定用户数据是否存在,以使其成为并发调用,我正在使用 Bluebird Promise.Prop,如下所示。使用 sequelize ORM 加入数据。

Promise.props({
  user: (()=>{
    return User.findOne({
        where: {username: req.user.username}

    });
  }),
  comments: (()=>{
    return comments.findOne({
        where: {username: req.user.username}

    });
  })
}).then((result)=> {
    console.log(result.user.name, result.comments.count);
});

我也尝试过嵌套 promise ,但没有成功。喜欢
 Promise.props({
   user: (()=>{
    return User.findOne({
        where: {username: req.user.username}

    }).then((user)=>{
      console.log(user.name); // even here i am getting undefined
    });
  }),
  comments: (()=>{
    return comments.findOne({
        where: {username: req.user.username}

    });
  })
}).then((result)=> {
    console.log(result.user.name, result.comments.count);
});

最佳答案

您不清楚 result.user 是否未定义,或者 result.user.name 是否未定义。
我期待后者。

你将一个带有 2 个键的对象传递给 Promise.props。
但是这两个键都是一个函数,而不是一个 promise 。所以 promise.props 看到的是函数,而不是 promise 。
结果应该仍然具有 2 个功能。

尝试

Promise.props({
  user: User.findOne({
        where: {username: req.user.username}
  }),
  comments: comments.findOne({
        where: {username: req.user.username}
  })
}).then((result)=> {
    console.log(result.user.name, result.comments.count);
});

其他好的方法是 Promise.all,或者如果你知道你有多少 promise ,那么使用 Promise.join
Promise.join(
  User.findOne({
        where: {username: req.user.username}
  }),
  comments.findOne({
        where: {username: req.user.username}
  }),
  (user, comment) => {
    console.log(user.name, comments.count);
  }
);

关于promise - 使用 Sequelize findOne 方法在 Bluebird promise 中进行并发调用。返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052575/

相关文章:

javascript - Node js 没有解决 promise 数组

javascript - 这段代码如何使用 promises 顺序获取 url 并将其顺序加载到 html 中?

mysql - 使用 sequelize.literal() 的替换

node.js - 在 forEach 循环中运行 sequelize 查询。无法处理结果

javascript - 在jscript中访问mariadb COLUMN_JSON数据

performance - Bluebird vs async.js 性能

javascript - Bluebird promise 链 : 'Catch' with Result

javascript - 对 Promise 处理的插入/创建进行 Sequelize 外键约束

javascript - Node.js/Sequelize.js/Express.js - 如何插入多对多关联? (同步/异步?)

javascript - 警告 : a promise was created in a handler at but was not returned from it [bluebird]