1

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

So it is a more structured approach for handling data, errors, etc? Because as you have mentioned callback hell is not fun.
Yeah, I agree. In my opinion it's just an elegant hacky way to deal with data for languages which suffer from this "problem".
Also a simple implementation: opensourceconnections.com/2014/02/16/…
That is a nice article you have provided. It definitely makes a lot more sense now that you have explained it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.