0

所以我是 Javascript 的新手,并试图制作一个不和谐的机器人。这是一个非常小的部分,说明了我的问题:

    module.exports = {
    name: "match",
    category: "LOL",
    description: "Give Summoner's Data to User",
    run: async (client, message, args) => {
        var username = `${args}`
        var regionID= "na1"

        pyke.summoner.getBySummonerName(username, regionID).then(data => {
            return pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1").then(result => {
                try {
                    console.log(result)
                } catch (err) {
                    console.error(`${args} isn't in game!`)
                }
            })
    })
    }
}

我希望查看是否导致错误,它将向控制台发送代码。但是,我得到一个UnhandledPromiseRejectionWarning. 我的问题是为什么我不能捕获错误并将代码发送到控制台?

所以这就是我尝试的命令

const property1 = result.participants.summonerName
            const BResult = property1
            let FResult =  JSON.stringify(BResult)
            message.channel.send(FResult)

当我尝试时,我得到一个错误,说这个人不在游戏中。我知道这是错误的,因为它们在游戏中。

所以我更进一步并尝试这样做。

const property1 = result.participants[summonerName]
            const BResult = property1
            let FResult =  JSON.stringify(BResult)
            message.channel.send(FResult)

我仍然从最后一个得到相同的结果。我也尝试这样做const property1 = result.summonerName,但效果不佳。

4

1 回答 1

2

而是尝试pyke.spectator.getCurrentGameInfoBySummonetry/catch. 此示例try/catchawait关键字一起使用:

module.exports = {
  name: "match",
  category: "LOL",
  description: "Give Summoner's Data to User",
  run: async (client, message, args) => {
    const username = `${args}`;
    const regionID = "na1";

    return pyke.summoner.getBySummonerName(username, regionID).then((data) => {
        try {
            const result = await pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1");
            console.log(result);
        } catch (err) {
            console.error(`${args} isn't in game!`);
        }
    });
  },
};

否则,您可以尝试仅使用 Promisecatch来处理错误:

module.exports = {
  name: "match",
  category: "LOL",
  description: "Give Summoner's Data to User",
  run: async (client, message, args) => {
    const username = `${args}`;
    const regionID = "na1";

    return pyke.summoner.getBySummonerName(username, regionID).then((data) => {
        return pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1")
            .then(result => {
                console.log(result);
            })
            .catch(err => {
                console.error(`${args} isn't in game!`)
            }); 
    });
  },
};

您可以使用JSON.stringify对对象进行字符串化,并且可以使用各种不同的方法(例如解构)来提取您只想返回的特定属性,并结合创建/返回新对象:

// extract specific properties from `result`
// This is use ES6 destructuring, but you can use dot notation instead or whatever you prefer
const { property1, property2, property 3 } = result;
// return the stringified object only with the properties you need
const payload = { property1, property2 ,property };
return JSON.stringify(payload)
于 2020-07-18T16:57:36.133 回答