gpt4 book ai didi

node.js - 使用 sequelizejs 查询返回未定义

转载 作者:行者123 更新时间:2023-12-03 22:42:05 24 4
gpt4 key购买 nike

一个 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 talkId 是 [object Promise] 。

如何在 .then() 函数之外获取和使用该 Promise?

最佳答案

您正在尝试使用 checkRoom() 作为同步函数,但事实并非如此(就像大多数处理 Node 中 I/O 的函数一样)。

相反,您应该返回 findOne() 返回的 promise 并在您的调用代码中处理该 promise 的解析(和拒绝):

// 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
...
})

关于node.js - 使用 sequelizejs 查询返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com