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



我想验证多个表中特定用户数据的存在,使其成为我使用Bluebird Promise的并发调用。道具如下。使用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.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.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.al加入

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本身,而不是解析值。结果需要收集在承诺决议中,然后传递。

// collect values in this object
const values = {};
// run all promises
Promise.all([
model.findOne()
.then((val) => {
// assign result 1
values.val1 = val;
return Promise.resolve();
}),
model.findOne()
.then((val) => {
// assign result 2
values.val2 = val;
return Promise.resolve();
}),
])
.then(() => {
// the values will be collected here.
console.log(values);
});

最新更新