วันศุกร์ที่ 20 ธันวาคม พ.ศ. 2556

Promise and Deferred in AngularJS


Reference


Very simple example of using promises
http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

An example of using notify() to update progress
http://nurkiewicz.blogspot.com/2013/03/promises-and-deferred-objects-in-jquery.html

Official document of AngularJS promise/deferred
http://docs.angularjs.org/api/ng.$q


compare code : callback .vs. promise


CallbackPromise
in function
var getMessages = function(callback)
{
    $timeout(function() {
        callback(['Hello', 'World!']);
    }, 2000);
}
in function
var getMessages = function()
{
    var deferred = $q.defer();
    $timeout(function() {
        deferred.resolve(['Hello', 'World!']);
    }, 2000);
    return deferred.promise;
}
in controller
getMessages(function(messages) {
    $scope.messages = messages;
});
in controller
getMessages().then(function(messages) {
    $scope.messages = messages;
});

promise with notify()


in function
var getMessages = function() {
    var deferred = $q.defer();

    var id = setInterval(function() {
        deferred.notify();
    }, 1000);

    $timeout(function() {
        clearInterval(id);
        deferred.resolve(['Hello', 'World!']);
    }, 9000);
    return deferred.promise;
}


in controller
HelloWorldP.getMessages().then(
function(messages) { // function for resolve() callback
    $scope.p.messagesp = messages;
}, 
null, // function for error callback
function(){// function for notify() callback
    $scope.p.waiting_msg += '.';
});

ไม่มีความคิดเห็น:

แสดงความคิดเห็น