Z
Z
zlFast2016-04-04 19:02:24
JavaScript
zlFast, 2016-04-04 19:02:24

How to make a function return the result of a query?

I do this: If my function looks like this, then the test variable will be equal to 4:
var test = myFunc(2);

function test(id){
return id*2
        }

But I need to send a request inside the function, I try this, it doesn't work:
function test(id) {
            return  myService.getById(id).then(function (result) {
                return result[0].name;
            });
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-04-04
@bingo347

Your function will return a promise, get the result through then

function test(id) {
            return  myService.getById(id).then(function (result) {
                return result[0].name;
            });
}

test(2).then(function(test) {
  //some code
});

I
Ilya, 2016-04-04
@rpsv

In fact, I’m not very familiar with promises, but in this context, the task is better to solve with an event approach:

function test(id) {
  return  myService.getById(id).then(function (result) {
      onEndTest(result);
  });
}

function onEndTest(result) {
  // обработка результата
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question