简体   繁体   中英

Using AngularJS Promise

I am currently attempting to learn the AngularJS framework and I keep hearing about something called "promise". I have researched a little about it, although I cannot seem to find a thorough explanation to how and when to use "promises".

Can anyone please explain and provide a solution between using a promise, and not using a promise. What is the advantage of using a promise over not using one?

All answer are appreciated.

Thanks.

promises implementation basically provides an interface which define at least one method 'when' that return therefore, a "Promise", thus a result from an async operation.

Advantages are better code readability (and production as well), better reuse of the results without incurring on the scaring "callbacks hell", chainabilty, etc...

A simple scenario with jQuery:

without promises

$.ajax({
    url: someurl,
    success: function(data)
    {
        //do something with data
    }
});

with promises

var p = $.ajax({ url: someurl });

$.when(p).then(function(data)
{
    //do something with data    
});

However, a better explanation: http://wiki.commonjs.org/wiki/Promises/A

The official documentation says that

The promise api allows for composition that is very hard to do with the traditional callback (CPS ) approach. For more on this please see the Q documentation especially the section on serial or parallel joining of promises.

http://docs.angularjs.org/api/ng/service/$q

I think the easiest explanation could be that it's a much better and cleaner way to do a serial or very complex callbacks than the traditional way.

This is the link you can read more about the benefit of using promise:

promises specification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM