model.js文件包含此模型:
exports.Conversations = db.sequelize.define('conversations', {
room_id: {
type: db.Sequelize.STRING
},
user_id: {
type: db.Sequelize.STRING
},
friend_id: {
type: db.Sequelize.STRING
},
}, {
timestamps: true,
createdAt:'created_at',
updatedAt:'updated_at',
deletedAt:'deleted_at',
freezeTableName: true // Model tableName will be the same as the model name
});
在query.js中我有以下功能:
exports.checkRoom = function(user_id,friend_id) {
models.Conversations.findOne({ where: { $or: [{user_id: user_id , friend_id: friend_id}, {user_id: friend_id , friend_id: user_id}] }} ).then(function(conversation) {
return conversation;
});
}
相当于:
SELECT
"id", "room_id", "user_id", "friend_id", "created_at", "updated_at"
FROM
"conversations" AS "conversations"
WHERE
(("conversations"."user_id" = '127' AND "conversations"."friend_id" = '124')
OR ("conversations"."user_id" = '124' AND "conversations"."friend_id" = '127'))
LIMIT 1;
当我在cluster.js中对该功能进行调用时
var conversation = query.checkRoom(data.userId,data.friendId));
我的谈话未定义。
找到几个解决方案来捕获对象Promise但没有用。
期待您的回答。
编辑
管理这样做但是在调用查询时我想将该答案添加到var中,以便稍后可以使用它。如果现在我正在做类似var
的事情conversationId = query.checkRoom(data.userId, data.friendId).then(function(conversation) { return conversation.dataValues.id; })
我知道我的var conversationId是[object Promise]。
如何在.then()函数之外获取和使用Promise?
答案 0 :(得分:0)
您尝试使用checkRoom()
作为同步函数,它不是(与大多数处理Node中I / O的函数一样)。
相反,您应该返回findOne()
返回的承诺,并在您的调用代码中处理该承诺的解析(和拒绝):
// query.js
exports.checkRoom = function(user_id, friend_id) {
return models.Conversations.findOne({ where: { $or: [{user_id: user_id , friend_id: friend_id}, {user_id: friend_id , friend_id: user_id}] }} );
}
// calling code
query.checkRoom(data.userId, data.friendId).then(function(conversation) {
// do something with the database result
...
})