0

我目前正在为我的机器人制作商店,并且正在执行购买命令。我决定将用户的库存作为对象存储在数据库中,但是,当我第一次尝试从商店(在本例中为风扇)购买商品时,它会生成(空白)对象,但随后会返回:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fan' of undefined

这是代码:https ://github.com/boomermath/grapeoverhaul/blob/master/commands/t.js

module.exports = {
    name: 't',
    description: 'dig to earn stars',
    cooldown: 0,
    execute(message, args, d) {
//blank object to initialize in the db
const blankObj = {}
//items in the shop and their cost
const itemCost = {
    fan: 100,
    orangedetector: 100,
    mangodetector: 50,
    carrotdetector: 50,
    starmagnet: 100,
    starmill: 400
}
async function buy() {
     //get person's inventory
    let have = await d.items.get(message.author.id);
    //if they arent in the db, initialize
    if (have === undefined || have === null) {
    await d.items.set(message.author.id, blankObj)
    }
    //argument parsing, get item and number of items user wants
    let regex = /\d+/g;
    let numberOfItemsRaw = args.join(' ').match(regex);
    let numberOfItems = parseInt(numberOfItemsRaw);
    let item = args.join(' ').replace(numberOfItems, '').replace(' ', '');
     //if they don't specify a number assume one.
      if (numberOfItemsRaw === NaN || numberOfItemsRaw === null || numberOfItemsRaw === undefined) {
        numberOfItems = 1;
    }
    //because some idot is gonna put 0, i guarantee it
    if (numberOfItems === 0) {
        message.channel.send('ok karen');
        return;
    }
    //if item is not in the shop, then big oof
if (!Object.keys(itemCost).includes(item)) {
        message.channel.send("dude that's not an item in the shop");
        return;
    }
    //total cost
    let total = itemCost[item] * numberOfItems;
    //if ur broke
    if (total > await d.users.get(message.author.id)) {
        message.channel.send('you donut have enough money, rip');
        return;
    }
    //take money
    d.addMoni(message.author.id, -total)
    //intialize item property to store item
    if (have[item] === undefined || have[item] === null) {
    have[item] = 0;
    }
   //give item(s)
    have[item] += numberOfItems
   //put in db
    d.items.set(message.author.id, have);
    message.channel.send(item);
    message.channel.send(numberOfItems);
}
buy();
    }
};

如何修复它以使其不返回未定义的错误?

4

1 回答 1

0

您忘记在为空或未定义have时进行初始化。await d.items.get(message.author.id)

//get person's inventory
let have = await d.items.get(message.author.id);
//if they arent in the db, initialize
if (have === undefined || have === null) {
    await d.items.set(message.author.id, blankObj);
    have = blankObj; // <<
}

因此,haveundefined您尝试评估have[item].

于 2020-10-22T14:41:47.397 回答