$ q promises - Object is not a function
I wanted to run sample promises from https://docs.angularjs.org/api/ng/service/$q , here is my code:
angular.module('testControllers').controller('testCtrl', ['$scope', '$q', function($scope, $q) {
function asyncGreet(name) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
setTimeout(function() {
if (true) {
resolve('Hello, ' + name + '!');
} else {
reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
});
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
console.log('Success: ' + greeting);
}, function(reason) {
console.log('Failed: ' + reason);
});
}
Chrome keeps telling me: TypeError: Object is not a function
What did I do wrong with the sample?
+3
source to share
2 answers
Make sure you are using angularjs in 1.3 version at least see demo below
var app = angular.module('app', [])
.controller('firstCtrl', function($scope, $q) {
$scope.ver = angular.version.full;
$scope.message = ""
$scope.asyncGreet = function (name) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
setTimeout(function() {
if (true) {
resolve('Hello, ' + name + '!');
} else {
reject('Greeting ' + name + ' is not allowed.');
}
}, 1500);
});
}
promise = $scope.asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<div ng-app="app">
<div ng-controller="firstCtrl">
Angular ver: {{ver}}
</div>
</div>
+2
source to share
See example below
var app = angular.module('app', []);
app.controller('fCtrl', function($scope, $q) {
$scope.test = true;
function asyncGreet(name, test) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
var deffered = $q.defer();
setTimeout(function() {
if (test) {
deffered.resolve('Hello, ' + name + '!');
} else {
deffered.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deffered.promise;
}
$scope.action = function() {
var promise = asyncGreet('Robin Hood', $scope.test);
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
};
$scope.action();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<input type="radio" ng-model="test" ng-value="true" ng-change="action()" />TRUE
<input type="radio" ng-model="test" ng-value="false" ng-change="action()" />FALSE
</div>
</div>
-2
source to share