我想验证来自多个表的特定用户数据是否存在,以使其成为并发调用,我正在使用 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/