Home > OS >  (node:152) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undef
(node:152) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undef

Time:12-01

(node:152) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined (node:152) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

error when run -rig in discord

const NicehashJS = require('./lib/api.js')
const Discord = require('discord.js');
const { default: axios } = require('axios');
const client = new Discord.Client();
const moment = require('moment-timezone');

const botToken = ''

const apiKey = ''
const apiSecret = ''
const organizationId = ''
async function rigStats(rigName, message) {
    const rawResponse = await nhClient.getMiningRigs()
    const data = rawResponse.data.miningRigs
    var stats


client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on("message", async message => {
    var args = message.content.substring(1).split(" ");
    if (message.author.bot) return;

    if (message.content.startsWith("-rig")) {
        rigStats(args[1], message)
    }
})
    for (i in data) {
        if (data[i].name == rigName) {
            rig = {
                id: data[i].rigId,
                rigName: data[i].name,
                status: data[i].minerStatus,
                unpaid: data[i].unpaidAmount,
                profitability: parseFloat(data[i].profitability).toFixed(8),
                stats: []
            }

            await axios.get('https://api.coindesk.com/v1/bpi/currentprice/myr.json')
                .then(resp => {
                    rig.profitability = {
                        "BTC": data[i].profitability,
                        "USD": parseFloat(data[i].profitability * resp.data.bpi.USD.rate_float).toFixed(2),
                        "MYR": parseFloat(data[i].profitability * resp.data.bpi.MYR.rate_float).toFixed(2)
                    }
                })

            if (rig.status !== 'OFFLINE') {
                for (x in data[i].devices) {
                    if (data[i].devices[x].status.enumName == 'DISABLED') {
                        rig.stats.push({
                            gpu: data[i].devices[x].name,
                            status: data[i].devices[x].status.enumName,
                            temp: '-',
                            load: '-',
                            power: '-',
                            hashrate: '-',
                            algo: '-'
                        })
                    }
                    else {
                        rig.stats.push({
                            gpu: data[i].devices[x].name,
                            status: data[i].devices[x].status.enumName,
                            temp: parseFloat(data[i].devices[x].temperature % 65536).toFixed(0)   '°C',
                            load: parseFloat(data[i].devices[x].load / 65536).toFixed(0)   '%',
                            power: `${data[i].devices[x].powerUsage}W`,
                            hashrate: parseFloat(data[i].devices[x].speeds[0].speed).toFixed(2)   data[i].devices[x].speeds[0].displaySuffix,
                            algo: data[i].devices[x].speeds[0].algorithm
                        })
                    }
                }
            }

            stats = rig
        }
    }

    var embed = {
        "title": `Rig Stats`,
        "url": `https://www.nicehash.com/my/mining/rigs/${stats.id}`,
        "color": 0,
        "footer": {
            "text": moment.tz('Asia/Kuala_Lumpur').format("HH:mm:ss")   " MYT"
        },
        "fields": [
            {
                "name": "Rig Name",
                "value": `${stats.rigName}`,
                "inline": true
            },
            {
                "name": "Rig ID",
                "value": `${stats.id}`,
                "inline": true
            },
            {
                "name": "Status",
                "value": `${stats.status}`
            },
            {
                "name": "Profitability",
                "value": `BTC ${parseFloat(stats.profitability.BTC).toFixed(8)}\nUSD ${parseFloat(stats.profitability.USD).toFixed(2)}\nMYR ${parseFloat(stats.profitability.MYR).toFixed(2)}`
            }
        ]
    }

    for (i in stats.stats) {
        embed.fields.push({
            "name": `GPU: ${stats.stats[i].gpu}`,
            "value": `\`\`\`Status: ${stats.stats[i].status}\nTemperature: ${stats.stats[i].temp}\nLoad: ${stats.stats[i].load}\nPower: ${stats.stats[i].power}\nHashrate: ${stats.stats[i].hashrate}\nAlgorithm: ${stats.stats[i].algo}\`\`\``,
            "inline": true
        })
    }

    message.channel.send({ embed })
}

CodePudding user response:

Try checking the length of data. Seems to me like the loop doesn't run, and stats is still set to undefined.

CodePudding user response:

// Please try it with following approach.

var stats;
if (data.length < 1) {
   return;
}
let index = data.findIndex(item => (item.name === rigName) === true)
if (index > -1) {
    stats = {
        id: data[index].rigId,
        rigName: data[index].name,
        status: data[index].minerStatus,
        unpaid: data[index].unpaidAmount,
        profitability: parseFloat(data[index].profitability).toFixed(8),
        stats: []
    };
    const m = await axios.get('https://api.coindesk.com/v1/bpi/currentprice/myr.json');
    stats.profitability = {
        "BTC": data[index].profitability,
        "USD": parseFloat(data[index].profitability * m.data.bpi.USD.rate_float).toFixed(2),
        "MYR": parseFloat(data[index].profitability * m.data.bpi.MYR.rate_float).toFixed(2)
    }
    ....
}

var embed;
if (stats.hasOwnProperty("id")) {
    // put your json here.
}
  • Related