node.jsvk

Why Promise???? Help me


decided to start learning node js and at the same time writing a bot in VK. I wanted to make a function that displays the user's first and last name, but I get some kind of Promise. maybe this is a stupid question, but still.

const VkBot = require('node-vk-bot-api');

const bot = new VkBot('токен вк');

async function get_username (user_id) {
    var act = await bot.execute('users.get', {
        'user_ids': user_id,
    });

    return act;
    // return act.first_name + ' ' + act.last_name;
}

bot.event('message_new', (ctx) => {
    var text = ctx.message.text;
    var peer_id = ctx.message.peer_id;
    var user_id = ctx.message.from_id;
    // console.log(peer_id + ' | ' + get_username(user_id) + ' | ' + text);
    console.log(get_username(user_id))
});


bot.startPolling();

Solution

  • You need to wait for get_username:

    bot.event('message_new', async ctx => { // Callback async
        const text = ctx.message.text;
        const peer_id = ctx.message.peer_id;
        const user_id = ctx.message.from_id;
        console.log(await get_username(user_id)); // Wait for get_username
    });