Is promise a closure? - javascript

In closure tag wiki page, it reads "jQuery itself is one big closure."
But is promise a closure as well? Could you please explain why or why not? This is how I understand closure: assign a function to a variable and reuse it with different environments. Promise does that with $.ajax(), but I could not find anywhere in stackoverflow where promise is introduced as a closure. Maybe because there are other features of promise like $.Deferred(), resolve(), and fail() to expand its functionality beyond a simple function passing?

Closures
This is how I understand closure: assign a function to a variable and reuse it with different environments.
That's not a strictly accurate definition of a closure.
A closure is a function that has access to a referencing-environment. In Javascript, that means a function that is returned by another function and has access to the original functions scope. there are other SO questions that describe this very well
Closure's are general purpose structures that can be used in a variety of ways. One of their biggest benefits is that they protect private scope, which is why libraries like jQuery are often written as closures, so that they don't need to expose all their functions globally.
Promises
Promises are a different concept. They are a way of structuring asynchronous code to make it easier to follow the flow. A promise object in particular is an object that provides functions to chain operations in a clear and easy to read way. A promise might be implemented using closures, but it does not have to be. For instance here is an implementation that does not use closures:
https://gist.github.com/814052/690a6b41dc8445479676b347f1ed49f4fd0b1637
whereas jQuery's implementation uses at least one closure, but isn't really based on them
http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.Deferred
Conclusion
Promises and Closures aren't directly related concepts. Closure's are a programming technique that might be used in a Promise implementation. In the end it is neither impossible or necessary to implement it like that.

You wouldn't ask if a birdhouse was a 2x4, even if you used one to make it. The same can be said of promises and closures. Promises make use of closures to retain references to state, callbacks and other such things.

Because of the nature of JavaScript, being asynchronous that is, we are provide much power by the language and it's runtimes. First off, a Promise in jQuery, although it is not unique to jQuery, is an object that will as the documentation puts it, observe when all actions of a certain type bound to the collection, queued or not, have finished. This means you can use this object to know when to continue after a set or queue of items has finished some behavior. Now a Closure on the other hand is not unique to jQuery, but is rather a JavaScript construct, one that combines two things: a function, and the environment in which that function was created. This means that not only executing a function but doing so in possibly an entirely different context.

Closures and Promise are different concepts. Closures refers to scope of variables where as promise are used to 'promise' that an act on something will occur when it is done on an asynchronous action. Since Javascript is non-blocking (not asynchronous --edit), it will not wait for a function to get a response if it needs to access the internet or disk, that said you can have a promise execute after something is done.

Related

will it be possible to drop async/await in javascript and make async transparent?

I've been thin lately about async/await lately and its case is similar to references.
In javascript there're no pointers, derefecence operators etc. that exist in low-level languages which makes javascript look simpler because it pretends that a variable stores a value for an object while in truth it stores reference to an object and magically resolves it to the object when it notices you actually want to get the data. So it looks as if the variable stored the object itself.
Pretty same situation can be observed with promises: when you have a promise stored in some variable, you actually don't care about the promise itself - you care about its value.
AFAIK there are no pointers in javascript because they were confusing and could be abstracted away so they were. Same goes for promises.
Instead of doing
const data = await fetch("endpoint");
you could be doing
const data = fetch("endpoint");
because javascript would figure out that what you want is the data returned by the fetch. Promises and async/await actually might become language's internal implementation detail.
Will it be possible (meaning can it be implemented in javascript)?
Is there a language that already does this?
Would you want this to land in javasrcipt?
It's extremely unlikely that javascript would support this pattern. It's current approach to async code is so deep, that having 'explicit await' everywhere would really make javascript no longer javascript. I do think it might be possible to come up with a language that compiles down to javascript.
If you're looking for a language that does do this, take a look at Go. It's a much saner model for asynchronous programming because it was considered from the start. In javascript, promises and async/await were tacked on much later.
9 times out of 10 you will want to 'await' a asynchronous function, so in go every function is 'awaited'. If you don't want to 'await' a function, you call the function like this:
go foo()
So comparing Go and Javascript, the go and await keywords are very similar, but used for opposite cases.
In go, the async keyword in front of functions is also not needed.

Are there any potential memory leaks when using deferreds?

I get a jQuery.Deferred somewhere in my code, and I add several callbacks to it which are member methods of short-lived objects. I was wondering if there are any kind of memory leak potential in this situation, similarly like in .NET event handlers.
I was checking the code of jQuery, but haven't seen any part where callbacks are cleared. I didn't even find where the lifecycle of a deferred object should end.
Could anyone please shed some light on this topic?
EDIT
As I'm thinking about it, it narrows down to this question. In JavaScript, will holding a reference to a member function of an object (not prototype) deny the object from being GC-d? Because jQuery seems to hold these function references in the callbacks of the deferred object.
I haven't seen any part where callbacks are cleared.
The callbacks are cleared when the promise is settled (fulfilled or rejected).
I didn't even find where the lifecycle of a deferred object should end.
The lifecycle of a promise ends when nothing holds a reference to it any more.
There are generally two things that hold a reference to it: the resolver (e.g. timeout, ajax request etc) that eventually will settle the promise, and entities that store the promise because they want to use it (i.e. its result) later. The promise object in turn holds a reference to all the callbacks (until settled), and to the result value (since settled).
A leak can occur if the promise is never resolved, has callbacks attached to it, and is prevented from being garbage-collected by some references. That's very rare though.
In JavaScript, will holding a reference to a member function of an object (not prototype) deny the object from being GC-d?
No, in general not. There are no "members" in javascript, just plain standalone functions.
Though of course the function, when being a closure, could hold a reference to the object, and would keep it from being collected.
I'll answer my question because it seems to be a simple one after some thinking. Actually JavaScript functions don't belong "tightly" to the objects where they're defined, unless they are manually bound with Function.prototype.bind for example, but that's another case.
So if functions are living their own life, holding a reference to them should not deny collecting the object where it was originally defined.
Also I have to note that this all doesn't even matter if I don't hold a direct or closured reference to the deferred object itself, because then whenever it's done the job (resolved/rejected) it will be collectible.
Please someone more experienced correct me if any assumption is wrong here.
From what I've seen (and some light reading: Do never resolved promises cause memory leak?), there is negligible impact from unresolved Promises -- or Deferrereds -- unless you are:
Creating a large number: hundreds of instances of any object are a drag that requires special handling and design
Maintaining references to instances that prevent a GC run from cleaning up any out-of-scope items

What is a function that returns a promise called?

What do you call a function which returns a promise?
This is not the start of a joke
In the javascript community I've seen a function that returns a promise called being "thenable" enough times that I think "thenable" when I'm coding. It's a thenable function.
I like this name for a number of reasons:
1) Thenable describes the functional behaviour. If it returns a promise, you can call "then" on it.
2) It's unique. Promises aren't exactly monadic, so monad isn't appropriate. "Async" is more of a super class of functions and doesn't help describe the nature of a Promise. But "thenable" is uniquely Promisely.
3) I also like that it's not repeating Promise everywhere, (Promissory, Promisified, Promise Function, etc.) which is approaching a circular definition IMO. Being able to google one word which has one specific meaning is really nice.
Well...
The current answers aren't really correct. The truth of the matter is there is no short clever name for "function that returns a promise" that is in the consensus of the JS community.
In JavaScript
The spec doesn't name them in a special way, no documentation of any popular library names them in a special way. The promises specification does not name them in any special way.
The origin of promises
From the other hand, if we check the literature branch originating from Liskov and Shrira, they don't, and neither do Bogle nor Zondervan use any term other than "getting a promise" or "getting the future" for it (they do use claim for extracting the value).
If we check Mark Miller's work he does not use any terms for it either.
Other languages
In other languages things don't fare better. C# has no special name for methods that return Tasks (its promises). It does have "async functions" for functions that return async/await but that's only a strict subset. No special name in Scala, no special name in Python, no special name in Java and so on. The only thing close was parse's Android API naming their promises' then callbacks Continuation but that's hardly meaningful in this context.
Name suggestions
If it makes you feel any better - we don't have a name for something that returns an array either.
"Monadic functions" - Lots of functions can return monads that are not promises, moreover promises aren't really monads - they don't actually conform in their current form to monad laws nor does then make a valid bind. More importantly, very few JS developers even know what monads are and even fewer care.
"async function" - this might hold when (and if! it's not 100% sure now) the async modifier is added to the language. Right now and probably event then a lot of people consider things like setTimeout or fs.openFile to be async functions.
"Kleisli Arrows" - I took a type theory course and it covered this topic and I don't think me or any other students would call a function that returns a monad a Kleisli arrow. For one thing because it's an Arrow (yes yes, arrows are functions I get it).
Conclusion
To conclude, the people who invented promises, the people who specified them for JavaScript, the people who put that spec in writing, the spec itself, the promise libraries, the libraries written with those and the average user don't have any special name for it.
I think we can stick to A function that returns a promise.
If it makes you feel any better - we don't name "functions that return an int" either :)
In my experience, there are no individual words to describe functions that return a particular type. They are generally called "a function that returns a <Type>".
For example:
foo() is a function that returns a String
bar() is a function that returns a Number
baz() is a function that returns a Promise
In this context, Promise is being used similar to how an interface would in a strongly typed language.
Another example of a generic type being used would be
fizz() is a function that returns a collection
That's not to say that there can't be a word with a definition of "a function that returns a Promise", but there's no commonly used jargon to describe this.
"deferred function" is sometimes used to describe a function that returns promises or promise-like objects (i.e. jQuery's Deferred Object).
Functions that return promises can also be described by other more general words (in much the same way that a square can be described as a rectangle, parallelogram, rhombus, or quadrilateral).
Promises are monads, so they can be described as "monadic".
Promises are asynchronous, so functions that utilize them can be described as asynchronous as well.
Personally, I'd go with "promissory functions", as "promissory" means:
conveying or implying a promise
and I like the idea that the return value of such a function is "conveying a promise".
We call them asynchronous functions. Even if the function does nothing asynchronous itself, it at least returns a promise - an asynchronous value.
You can shorten that to async function, although that term is also used for the ES7 syntactic notation async function that creates functions which return promises implicitly (whose code can use await).
If you want to think of the type of functions that return monads (which promises are), you can call them Kleisli arrows. But you did ask a [javascript] question, not a [type-theory] one, did you?
Technically, a promise is a monad. Hence, a function that returns a promise is a monadic function.

How to think when working with promises

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

Javascript callback hell with setTimeout();

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.

Categories

Resources