K
K
krlljs2016-05-05 11:26:29
JavaScript
krlljs, 2016-05-05 11:26:29

How to return value from Promise in Javascript?

'use strict';

const VKapi = require('node-vkapi');
var urlencode = require('urlencode');
var _ = require('underscore');
 
const VK = new VKapi({
  token: 'a89e24c414d82ba1a3fad33989f833339dsdb6db615004dfa01de61f73cac48eabdff34e4e8bf846e1a2f'
});

var start = function(user_id) {
  VK.call('groups.get', {
    user_id: user_id,
  })
  .catch(e => {console.log(e)});
}

var b;
var a = start(343910101).then(res => {b = res});
console.log(b);

C:\Users\Общий\Desktop\vks>node gtp.js
undefined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2016-05-05
@krlljs

You are correct, except that you output b synchronously before it fills up.
As soon as you have promises and asynchrony in at least one function, forget about synchronous code, only .then() .

var b;
start(343910101)
.then(res => {b = res})
.then(() => console.log(b));

Z
Zas999, 2021-08-29
@Zas999

Here is the part of my code where I need to return a value:

const findMany = ({value, columns = [], findByColumn}) => {
            return new Promise((resolve, reject) => {
                let query =new QueryBuilder().select(columns).from("users")
                    .where(findByColumn, "=", value)
                    .get();

                __db.query(query, (error, results, fields)=>{
                    if (error) reject(error);
                    __db.end();

                    if(results.length <= 0) resolve(null);

                    let users = [];
                    results.forEach((item, index, array)=>{
                        users.push(new User(item));
                    });
                    resolve(users)
                });
            });
        }

id : ({value, columns = []}) => {
                return findOne({
                    value,
                    columns,
                    findByColumn : "id"
                });
            },

And then I get the value like this:
let user = await User.findBy().id({value : 1});
console.log(user);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question