0

I have created a small project, but I have some problems. I want to run some JavaScript code after my query. My code is like this:

Book.get({
    id: $stateParams.id,
    min: 0,
    max: 3
}).$promise.then(function(data){
    vm.list=data;
}).finally(function () {

});
vm.top=vm.list.name;

vm.top is undefined, because the query has not returned yet.

1
  • 1
    keep everything within a promise; since it's an asynchronous callback, it can return after few milliseconds or minutes - you can't assign a variable after it. vm.top is undefined because it runs before your callback Commented Apr 27, 2018 at 8:11

1 Answer 1

2

This is not how you should deal with asynchronous calls. The reason being is (in short) a JavaScript engine executes synchronous code first and then it executes asynchronous code.

Ideally you should wait until they accomplish and put your desired work inside their callback function. So over here you can either

  1. call your code inside .then of Book.get() function
  2. Or chain the promise and call desired code.

// 1. First way
var getBook = Book.get({id:$stateParams.id,min:0,max:3}).$promise.then(function(data){
  vm.list=data;
  // Put your code here
}).finally(function () {

});

// 2. Second way
getBook.then(function(){
   vm.top= vm.list && vm.list.name;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.