I've created a simple example of this with the below code. The goal is to be able to used the deferred
promise from Angular's $q
service but have $q
within a callback that itself returns a result that is to be handled in the main controller.
I recognize the error is clearly that the $q
's promise needs to be returned immediately so that it can "await" the result and that placing that promise within a callback inhibits it from being returned immediately. Thus, the code below is clearly an incorrect strategy.
My question is to ask what the best practice would be to achieve a comparable utility to the above described desire, including the presence of both a callback and need to return a promise.
function asyncGreet(name, cb) {
cb(name)
}
function okToGreet(name) {
return name.length > 10
}
var promise = asyncGreet('Robin Hood', function(name) {
var deferred = $q.defer();
setTimeout(function() {
deferred.notify('About to greet ' + name + '.');
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deferred.promise;
});
promise.then(function(greeting) {
console.log('Success: ' + greeting);
}, function(reason) {
console.log('Failed: ' + reason);
});