I am new to Javascript & AngularJS. I have a scenario as below:
$http.get('URL').success(function(data){
$scope.data = data;
});
$.fullCalender({
calendarData: $scope.data
});
In above code, I get blank for 'calendarData'
But I can resolve above issue as below:
$http.get('URL').success(function(data){
$.fullCalender({
calendarData: data
});
});
So, my doubt is: When we can resolve issue as above, why people go for promises. Sorry if its a dumb query.
Promises solve the famous callback hell issue. Callback hell really refers to 2 issues. The first is the idea that with callbacks you may sometimes need to nest callbacks and as such have very difficult to read code. Promises on the other hand can be chained which makes for much cleaner code.
Another issue is something called inversion of control. This is the big issue. The idea that in some cases the callback being called by some third party can be a scary thought. If for whatever reason there is some bug in said party , this bug will now leak in to your code.
An example would be if for whatever your reason your callback was getting invoked more than once. This can obviously be a fatal flaw. promises only execute the callback function once no matter what. In other words, reverting the inversion of control is a huge win with promises.
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
I'm working for the first time with async programming, specifically with promises in Javascript and I'm really confused with it. I'm still thinking like we do in C, PHP, C# and so on where for each step the next one can be sure of it's completion. This is easy to work, because if we have a code like that (in C# for example)
IEnumerable<Page> pages = pagesRepository.getAll();
we can be sure in the next line that all pages are available for us to use in the pages object. This makes life easier, because we can already do work with that data properly.
Now, in JS with promises we would have something like
var pages = dataService.getPages();
and this would not return the data, but just a promise which is very different. Of course we can add a callback with then but I'm getting confused, because somewhere else in my code I might need to reference this variable, and I cannot be sure when the callback will be called.
So how do we think when we deal with those things? Is there some tutorial or some videos out there that show in detail how to work with async programming with promises in JS?
Of course we can add a callback with then but I'm getting confused, because somewhere else in my code I might need to reference this variable, and I cannot be sure when the callback will be called.
You don't need to.
The "somewhere else code" will use .then() and yield a new promise for its result, relying on the pages promise. You can easily map the results, or chain other asynchronous tasks. Whenever you need to know about the timing of callbacks because of multiple dependencies, you should use your library's methods for composing promises, like all().
So how do we think when we deal with those things?
Think functional!
Every task in your program should explicitly and only depend on its inputs. A function should try to only use its arguments, not any global variables that contain state.
Is there some tutorial or some videos out there that show in detail how to work with async programming with promises in JS?
General Promise Resources in the wiki of the Q library is a very good start.
The simple answer here is that promises are similar to Task asynchronous programming in C#.
However instead of being able to use the 'await' operator, the 'then' function on a promise is analogous to using 'ContinueWith' to chain Tasks in C#.
Callbacks can get complicated to use across scopes, especially with extensive use of nested anonymous functions, so please give promises a go
Aloha. This is my first question here after eons of lurking. I apologize for the verbose but direct form of this question -- as well as the limitations on acceptable answers -- but I am here to contribute. I have a problem that other questions (for example How to avoid long nesting of asynchronous functions in Node.js or Chained callback readability in Javascript?) do not answer to my satisfaction.
I want to perform several Javascript callbacks so that I have a sequence of four actions occurring one after another. Here is the source:
var self = this;
fade(div, fadeIn, -20, function() {
load(unload, dataOut, -10, function() {
load(self, dataIn, 10, function() {
fade(div, fadeOut, 20),0);
unload = self;}
);}
);}
);
The load() and fade() functions are very similar except for internal semantic details, and they look something very similar to this:
function load(menuCategory, data, step, callback) {
menuCategory.parentNode.style.width = data+"px";
data += step;
if(dataIn <= data && data <= dataOut) {
setTimeout(function() { load(menuCategory,data,step,callback) }, 15);
} else if(callback && (typeof(callback) == 'function')) {
callback();}
}
I have several questions associated with this mess, but first let me give you the answers I am NOT looking for. Answers using jQuery are not acceptable. Answers using other timing or "synchronicity" frameworks or modules are not acceptable. Answers questioning the reason for blocking execution are not acceptable. Answers using languages other than Javascript are unacceptable. Non-abstract answers are acceptable, but the final solution will need to be as abstract as possible, meaning the answer must be able to act on a variety of similar but slightly different actions.
Here is my primary question:
Is there a function/object I could use to apply these actions sequentially, to cut down on the callback hell going on here? In other words, what would an object look like if the object/function were able to synchronously execute each action as it was individually iterated through it (i.e. passed to it)?
Secondary question:
Is anyone aware of how much this callback business looks like goto() in other languages? Meaning, this nesting of callbacks feels very awkward and inelegant to me. Is there a Javascript language construct either being developed or already developed that will reduce this crazy business? Callback nesting is some of the hardest logic flow to follow. It just feels awkward.
My goal here is a tight, elegant, attractive, homegrown Javascript object/function -- that I can call in a for() loop or equivalent -- to apply these operations on each action in sequence. If you've read this far I want to thank you for your time and consideration. :)
using setTimeout(func(),0) in order to execute synchronously
No. Either use func() for a synchronous execution, or setTimeout(func, 0) to queue the execution (which makes it asynchronous).
Is setTimeout(func[…],0) the "most elegant" way to put this action onto the execution queue for rendered webpage objects? In other words, is there a "more elegant" way to block execution (i.e. do these things sequentially)?
Yes, this is the standard method. However, this does not block execution, and has nothing to do with sequencing. If the execution is synchronous, just execute it, if not you will have to deal with the callbacks and queuing a new task does not help.
Is anyone aware of how much this callback business looks like goto() in other languages? Meaning, this nesting of callbacks feels very awkward and inelegant to me. Is there a Javascript language construct either being developed or already developed that will reduce this crazy business?
No, I'm not aware of other languages, but afaik goto is a synchronous, control-flow-structuring statement as does not deal with asynchronous actions.
But no, there are no JavaScript language constructs ("syntactic sugar") that help us around the continuation-passing style with its callback hell.
Is there a function/object I could use to apply these actions sequentially, to cut down on the callback hell going on here? In other words, what would an object look like if the object/function were able to synchronously execute each action as it was individually iterated through it (i.e. passed to it)?
My goal here is a tight, elegant, attractive, homegrown Javascript object/function -- that I can call in a for() loop or equivalent -- to apply these operations on each action in sequence.
Again you want "sequencially" instead of "synchronous" :-) Yes, there are [handcoded/homegrown] solutions which make dealing with callbacks easier. As those callback organisation libraries you mentioned do not satisfy you, I'd recommend to look into the very elegant and attractive Promise Api and its Deferred objects (see futures and promises for the concept).
I'm unsure why you're using setTimeout at all here. Its not necessary to queue callbacks. The following structure will work, assuming that fade() and load() handle callback execution correctly.
fade(div, fadeIn, -20, function() {
load(unload, dataOut, -10, function() {
load(self, dataIn, 10, function() {
fade(div, fadeOut, 20),0);
});
)};
)};
Another topic you should look into is Promises, also called deferreds and futures. Its essentially a coding pattern that specifically handles nested callbacks. At root, you create a Promise object that gets returned immediately, then when your method is done executing it fires a method on the promise that can then execute your next function. Its a different way of writing javascript, but easy to understand and very useful.
As it turns out, the practice that fits as the "best" answer to my question is events. In particular the practice I'm referring to is best described by EventEmitter on Node.js, or creating custom events and event listeners on client browsers. While the Promise API and its deference model is intriguing, it uses extensions to the language instead of core Javascript, which is what I was looking for here in particular (and thus why none of the previous answers -- despite their clarity -- support exactly what I was looking for).
This link (http://wekeroad.com/2012/04/05/cleaning-up-deep-callback-nesting-with-nodes-eventemitter) provides a very good example of what I was looking for. As well, I should mention the book "Async Javascript" by Trevor Burnham (http://www.amazon.com/Async-JavaScript-Trevor-Burnham/dp/1475247362), and "Secrets of the JavaScript Ninja" by John Resig and Bear Bibeault (http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X). These books provide extremely clear working examples of custom events and event handlers in client browsers that provide an elegant way around this "callback hell" I was referring to.
I made a function that takes a number of asynchronous data-retrieval-functions and calls a callback when all functions return their data.
I'm wrestling with the terminology though. I've found similar examples here on StackOverflow but none of them offer anything in the way of solid terminology.
Resources that illustrate the functionality:
Parallel asynchronous Ajax requests using jQuery
Javascript - synchronizing after asynchronous calls
Synchronizing event-based plugin calls in JavaScript
Related terminology: fork, wait, synchronize, semaphore.
What is a good name for this function?
How about "waitAll"? It's succinct, but it still gets the point across about what it does.
For the sake of being complete. There isn't really a good word for it (yet). But frameworks like jQuery and commonJS have adopted a deferred API that allows you to make eventual promises about asynchronous requests. This is what I'll be using.
You can find more info when you look at the documentation of the mentioned frameworks but it's roughly like this:
FW.when([asynchrnous_request, ... ]).then(do_something)
The then-clause will fire when all requests have returned successfully.
You'll probably want to do something with error handling and manually fulfilling (or rejecting) promises but this is beyond the scope of my question.