Understanding JavaScript Continuations

I am trying to solve the last exercise of this JavaScript Closure Tutorial , which talks about continuing the transfer.

This exercise:

Define a function called bothC, similar to seqC, that performs the functions fC and gC, as well as success and failure to continue. Functions fC and gC just succeed, and failures. Your bothC function should call both fC and gC no matter what, but only the success of the call if both of them succeed, and failure otherwise. Do not forget that your function will never return!

This seems to be the correct answer:

var bothC = function (fC, gC, success, failure) { fC( function() { gC(success, failure); }, function() { gC(failure, failure); } ); }; 

But why can't I do this?

 var bothC = function(fC, gC, success, failure) { fC(gC(success, failure), gC(failure, failure)); } 
+6
source share
3 answers

Every time you have a function followed by parsers around a set of arguments (even if there are no arguments, it is still a set of arguments), the JS message is execute immediately . This means that gC(success, failure) actually starts gC, and then returns all gC returned. fC(gC(success, failure), gC(failure, failure)); basically means "calling fC with returning gC(success, failure) and gC(failure, failure) as parameters

To prevent this action and still make it callable, you need to wrap it in function(){} (this can be anonymous or not). This will turn it into a returned and called object, and not just as a method call. fC(function() {gC(success, failure); }, function() { gC(failure, failure); } ); means: "call fC with a function that will call gC(success, failure) and a function that will call gC(success, failure) as parameters


Like FYI, Sussman and Steele showed that continuation and closure are, more or less, the same thing, the difference is mainly in the syntax (this was in the late 70s. Read Gabriel / Steele History of Lisp Page 33). JS has great closure syntax, but in my opinion, Python yield syntax is the best example of continuation in the currently popular language. Just saying it.

+5
source

Because it calls gC (instead of deferring) and passes its result to fC .

+2
source

The code will not work because it will immediately call gC twice when bothC is bothC . fC supposed to take two extensions, that is, they should be called functions, not the results of calling functions.

+2
source

Source: https://habr.com/ru/post/894561/


All Articles