0

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();
  • 1
    Does this answer your question? [Async function returning promise, instead of value](https://stackoverflow.com/questions/51338277/async-function-returning-promise-instead-of-value) – VLAZ Nov 10 '20 at 17:05
  • Also relevant: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) | [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321) – VLAZ Nov 10 '20 at 17:05

2 Answers2

1

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
});
pzaenger
  • 11,381
  • 3
  • 45
  • 46
0

I will answer your why.

Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks.

so in ES6 you can use async/await instead of callbacks, thats how you can achieve non blocking code.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
salman
  • 264
  • 1
  • 9