0

I'm attempting to execute a block of code outside of a function based on a variable obtained from a $http GET request but I'm struggling to achieve this.

$scope.myBooleanVariable = $http.get("url...");

if ($scope.myBooleanVariable) { // undefined
//perform something that must be outside of a function
}

This is a basic example of what I'm attempting to do, but with the http request being asynchronous the if case is always undefined(falsy). Is there any elegant way to achieve this?

warbob1991
  • 23
  • 4
  • For Angular in particular, you can look at [this answer](https://stackoverflow.com/a/37586557/3773011). However, the other higher-voted answers do a better job at explaining the concepts, but don't directly have examples for Angular. What you appear to be missing here are the concepts as much as the syntax. – Makyen May 20 '20 at 15:10

1 Answers1

0

You can define a promise handler with a success/error callback to await the response. In the inner function you can access the variables from the outside.

In Angular.js you can do it like:

$scope.myValue = null;

$http.get("url...").$promise.then(function(response) {
  $scope.myValue = response;
  console.log(response);
  // do your logic, myValue is now defined
});
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
  • I specifically mentioned that the logic I want to execute should not be in a function, as is the case if you use .then(function(... – warbob1991 May 20 '20 at 16:18
  • Why do you *specifically* have that restriction? But if you do, the answer is simple: It is not possible. The request is asynchronous and you need to execute the logic in a callback. You could use syntactical sugar with `await` which makes it look like it is not in a function, but internally it is exactly the same. Like mentioned in my answer, you can access the outer scope from within a function, so you don't have any drawbacks when using a function. – ssc-hrep3 May 20 '20 at 23:45