Answer the question
In order to leave comments, you need to log in
Is it possible in Angular to get the return value of an asynchronous function?
I'm trying to deal with JS and the first angular in particular. Wrote this code:
<button class="but" ng-click="Handler()">Button</button> <br />
<script>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.GetRespose = function () {
var temp = "foo"
$http.get('/Home/GetValue').seccess(function (data) {
alert(data);
temp = data;
})
return temp;
}
$scope.Handler = function () {
alert($scope.GetRespose())
}
})
</script>
Answer the question
In order to leave comments, you need to log in
seccess? Well, joking aside, you need to return the promise itself, return $http.get('/Home/GetValue'), and you will always return "foo". Then think for yourself a little, it helps a lot to display intermediate results in the console to understand what kind of magic is going on.
$scope.GetRespnose = function () {
return $http.get('/Home/GetValue')
}
$scope.Handler = function () {
alert($scope.GetRespose()) // посмотрите что будет в результате, надеюсь поможет
}
I agree with the previous author. Understand how promises and asynchronous code work in general.
Your GetResponse function doesn't really wait until the request is processed, but immediately returns the value "foo". So you get exactly what you wrote in your code. If you "pause" the execution of the function, then your users will curse you for a hung browser. It is better to make the alert be called only after the request is completed, i.e. in success.
let promise = new Promise((resolve, reject) => {
if(success){
resolve(success);
}else{
reject(new Error("Network connection error!"))
}
});
promise.then((data) => {
console.log("success");
}).catch((error) => {
console.log("error");
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question