Example: subsequent transmission style in JavaScript (1)

Source: Internet
Author: User

Currently, CPS has been discovered again as a programming style of a non-blocking (usually distributed) system.

I like CPS very much, because it is a secret weapon for me to obtain a doctorate. In, it helped me lose a year or two and some incalculable pains.

This article introduces the two roles played by CPS-as a non-blocking programming style in JavaScript and as an intermediate form of a functional language (Brief Introduction ).

The content includes:

◆ CPS in JavaScript

◆ CPS for Ajax Programming

◆ CPS used in non-blocking programming (node. js)

◆ CPS for distributed programming

◆ How to use CPS to implement exceptions

◆ Simple Lisp CPS Converter

◆ How to implement call/cc using Lisp

◆ How to implement call/cc using JavaScript

Read down to learn more.

What is a continuous transmission style?

If a language supports subsequent continuation, programmers can add control structures such as exceptions, backtracking, threads, and constructors.

Unfortunately, many of the subsequent explanations (including me) are vague and unsatisfactory.

Subsequent transmission style is the basis.

Subsequent transmission styles give subsequent code meanings.

Even better, programmers can discover their own subsequent transmission styles, if they are constrained by the following constraints:

No process is allowed to be returned to its caller -- always so.

A revelation makes programming in this style possible:

A callback method can be called when they return values.

When a process (procedure) prepares to "return" to its caller, it calls "current subsequent (current continuation)" When returning the value) "This callback method (provided by its caller)

One is followed by an initial type (first-class) Return Point.

Example: Identification Function

Consider the identifier function in the normal format:

  1. function id(x) {    
  2.          return x ;  

Then the subsequent transmission style is as follows:

  1. function id(x,cc) {  
  2.    cc(x) ;  

Sometimes, naming the current subsequent parameter ret makes the purpose more obvious:

  1. function id(x,ret) {  
  2.    ret(x) ;  

Example: simple factorial

Below is the standard Simple factorial:

  1. function fact(n) {  
  2.    if (n == 0)  
  3.      return 1 ;  
  4.    else 
  5.     return n * fact(n-1) ;  

The following is the implementation of the CPS style:

  1. function fact(n,ret) {  
  2.    if (n == 0)  
  3.      ret(1) ;  
  4.    else 
  5.     fact(n-1, function (t0) {  
  6.       ret(n * t0) }) ;  

Next, we will pass a callback method to "use" the function:

  1. Fact (5, function (n ){
  2. Console. log (n); // output 120 in Firebug
  3. })

Example: tail recursion factorial

Below is the tail recursive factorial:

  1. function fact(n) {  
  2.    return tail_fact(n,1) ;  
  3. }    
  4. function tail_fact(n,a) {  
  5.    if (n == 0)  
  6.      return a ;  
  7.    else 
  8.      return tail_fact(n-1,n*a) ;  

The CPS implementation method is as follows:

  1. function fact(n,ret) {  
  2.    tail_fact(n,1,ret) ;  
  3. }     
  4. function tail_fact(n,a,ret) {  
  5.    if (n == 0)  
  6.      ret(a) ;  
  7.    else 
  8.      tail_fact(n-1,n*a,ret) ;  
  9. }    

CPS and Ajax

Ajax is a web programming technology that uses an XMLHttpRequest object in JavaScript to extract data from the server (asynchronously. (The extracted data does not need to be in XML format .) CPS provides an elegant way to implement Ajax programming. With XMLHttpRequest, we can write a blocking process fetch (url), capture the content on a url, and then return the content as a string. The problem with this method is that JavaScript is a single-threaded language. When JavaScript is blocked, the browser is temporarily frozen and cannot be moved. This will lead to unpleasant user experience. A better way is to execute the fetch (url, callback) process, which allows (or the browser to render work, the provided callback method is called once the request is complete. In this way, part of the CPS conversion has become a natural encoding method.

Implement fetch

It is not difficult to implement the fetch process. The non-blocking mode or blocking mode operation depends on whether the programmer provides the callback method:

  1. /*
  2. For client-> server-side requests,
  3. Fetch is an optional blocking process.
  4. The process is blocked and the content on the url is returned only when a url is provided.
  5. If the onSuccess callback method is provided,
  6. The process is non-blocking and the file
  7. To call the callback method.
  8. If the onFail callback method is also provided,
  9. OnFail is called when a failure event occurs.
  10. */
  11. Function fetch (url, onSuccess, onFail ){
  12. // The callback method is asynchronous only when the callback method is defined.
  13. Var async = onSuccess? True: false; // do not complain about the inefficiency of the Code,
  14. // Otherwise, you will not understand the key .)
  15. Var req; // XMLHttpRequest object.
  16. // XMLHttpRequest callback method:
  17. Function processReqChange (){
  18. If (req. readyState = 4 ){
  19. If (req. status = 200 ){
  20. If (onSuccess)
  21. OnSuccess (req. responseText, url, req );
  22. } Else {
  23. If (onFail)
  24. OnFail (url, req );
  25. }
  26. }
  27. }
  28. // Create an XMLHttpRequest object:
  29. If (window. XMLHttpRequest)
  30. Req = new XMLHttpRequest ();
  31. Else if (window. ActiveXObject)
  32. Req = new ActiveXObject ("Microsoft. XMLHTTP ");
  33. // If asynchronous, set the callback method:
  34. If (async)
  35. Req. onreadystatechange = processReqChange;
  36. // Initiate a request:
  37. Req. open ("GET", url, async );
  38. Req. send (null );
  39. // If asynchronous,
  40. // Return the request object. Otherwise
  41. // Return the response.
  42. If (async)
  43. Return req;
  44. Else
  45. Return req. responseText;
  46. }

Example: extract data

Consider a program. The program needs to capture a name from the UID.

Fetch is used in the following two methods:

  1. // Blocking until the request is complete:
  2. Var someName = fetch ("./1031/name ");
  3. Document. write ("someName:" + someName +"
  4. ");

  1. // Do not block:
  2. Fetch ("./1030/name", function (name ){
  3. Document. getElementById ("name"). innerHTML = name;
  4. });

CPS and non-blocking Programming

Node. js is a high-performance JavaScript server platform on which blocking processes are not allowed.

Cleverly, the usual blocking process (such as network or file I/O) uses the callback method called through the result.

Part of the program's CPS conversion has contributed to the natural node. js programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.