Monday, 16 August 2021

Node.js & Puppeteer: TypeError: Cannot destructure property '' of '(intermediate value)' as it is undefined

I have a function that handles some pizza orders from a certain user. I divided it into two parts: getting data from the user and filling inputs, clicking buttons, etc.

const handleUserOrder = async (page, $, ctx) => {
    const {name, size, sauce} = await getUserOrder($, ctx)

    //absolutely unimportant and useless code for my issue goes below
}

The error appears in the first part of my function, i.e. getting data:

const getUserOrder = async ($, ctx) => {
    let titles = []
    $('.goods__list__title').slice(0, 30).each((index, element) => {
        const title = $(element).text().trim()
        titles.push(title)
    })
    await ctx.reply(`Ну ладно, держи список: \n\n${titles.map(title => title + ' (' + (titles.indexOf(title) + 1) + ')').join('\n')}`)
    await keyboard.sendMessage(ctx.from.id, 'Напиши номер той пиццы, которую ты выбрал.')

    const name = await getName(titles)
    await keyboard.sendMessage(ctx.chat.id, `Значит ${name}. Размер?`)
    const size = await getSize(ctx)
    await keyboard.sendMessage(ctx.chat.id, `Так, с размером определились. Может теперь выберешь соус?`)
    await keyboard.sendMessage(ctx.chat.id, 'Одну секунду...')
    const {sauce, order} = await getSauce(ctx)
    await keyboard.sendMessage(ctx.chat.id, `Вот твой заказ: ${order}.`)
    return {name, size, sauce}
}

As you can see, I've created three functions for each piece of data I need to collect. And this is the place where the error occurs.

const getName = async (titles) => {
    const options = await titles.map(title => `${titles.indexOf(title) + 1}`)
    await ctx.reply('Выбирай любую!', {
        reply_markup: {
            keyboard: new Array(titles.length).fill(0).map((e, i) => [{text: `${i + 1}`}]),
            resize_keyboard: true,
            one_time_keyboard: true,
            remove_keyboard: true,
        }
    })
    await bot.hears(options, async (ctx) => {
        return titles[parseInt(ctx.match[0]) - 1]
    })
}

I've recognized that I get this error only if the return method is situated on the last level of nesting. Otherwise, if I, for example, just give name some certain value, instead of choosing it as a user, it works absolutely fine, because there is no nesting at all.

Do you have any ideas on how can I fix it?

This is how my code looks with Promise (@ggorlen's advice):

const getName = async (titles, ctx) => {
    const options = await titles.map(title => `${titles.indexOf(title) + 1}`)
    await ctx.reply('Выбирай любую!', {
        reply_markup: {
            keyboard: new Array(titles.length).fill(0).map((e, i) => [{text: `${i +1}`}]),
            resize_keyboard: true,
            one_time_keyboard: true,
            remove_keyboard: true,
        }
    })

    return new Promise(res => {
        bot.hears(options, ctx => {
            res(titles[parseInt(ctx.match[0]) - 1])
        })
    })
}

And now after a little time passes after the function called I get this error:

(node:20076) UnhandledPromiseRejectionWarning: TimeoutError: Promise timed out after 90000 milliseconds
    at Timeout._onTimeout (/Users/mishashkarubski/WebstormProjects/pizza/node_modules/p-timeout/index.js:39:64)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:20076) 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)

(node:20076) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.



from Node.js & Puppeteer: TypeError: Cannot destructure property '' of '(intermediate value)' as it is undefined

No comments:

Post a Comment