TypeError:usert.addItem不是函数

时间:2019-01-23 23:39:21

标签: javascript node.js sequelize.js discord.js

尝试使用discord.js制作Discord机器人。我正在使用sequelize和sqlite创建一个数据库来存储数据。自定义函数似乎不起作用,终端认为它在实际定义时不是函数。可能有一个很明显的解决方案,但是我非常业余,经常遇到错误,但通常会解决这些错误。我什至无法确定问题的根源

此问题也适用于其他自定义功能

最令人困惑的一点是,对于完全相同的另一个bot的另一个文件夹,具有非常相似的代码和本质上相同的自定义功能,它可以工作!但是由于某种原因,它在这里不起作用。

// Defining these 
const { Users, ItemDB } = require('./dbObjects');



// The command that uses the function. It is worth noting that it finds the item and user successfully, proving that the problem is in users.addItem
const item = await ItemDB.findByPk(1);
const usert = Users.findByPk(message.author.id);
usert.addItem(item);

// The addItem function defined, in dbObjects file
Users.prototype.addItem = async function(item) {
const useritem = await UserItems.findOne({
    where: { user_id: this.user_id, item_id: item.id },
});

if (useritem) {
    useritem.amount += 1;
    return useritem.save();
}

return UserItems.create({ user_id: this.user_id, item_id: item.id, amount: 1 });
}; 

预期结果已成功添加到数据库,但终端返回:

(node:21400) UnhandledPromiseRejectionWarning: TypeError: usert.addItem is not a function

await之前添加Users.findByPk会随机返回。

2 个答案:

答案 0 :(得分:0)

您需要await Users.findByPk(message.author.id);

const { Users, ItemDB } = require('./dbObjects');



// The command that uses the function. It is worth noting that it finds the item and user successfully, proving that the problem is in users.addItem
const item = await ItemDB.findByPk(1);
const usert = await Users.findByPk(message.author.id);
usert.addItem(item);

// The addItem function defined, in dbObjects file
Users.prototype.addItem = async function(item) {
const useritem = await UserItems.findOne({
    where: { user_id: this.user_id, item_id: item.id },
});

if (useritem) {
    useritem.amount += 1;
    return useritem.save();
}

return UserItems.create({ user_id: this.user_id, item_id: item.id, amount: 1 });


答案 1 :(得分:0)

由于Users.findByPk(message.author.id)是一个承诺,它将执行返回到下一个序列代码,因此变量const usert尚未初始化,这导致usert.addItem()不起作用。

您需要将const usert = Users.findByPk(message.author.id)更改为usert才能完全初始化,然后可以使用addItem()函数:

const usert = await Users.findByPk(message.author.id);