Two callback functions for JavaScript asynchronous programming

Source: Internet
Author: User
Tags call back function definition readfile

The previous section on the principle of asynchrony basically put back the function is also a few words, this section mainly to give a few examples to materialize. Before starting, the first thing to understand is that in JavaScript, functions can be passed as parameters, which involves the concept of higher-order functions, and you can do it yourself.

The traditional synchronous function needs to return a result, which is implemented by the return statement, for example:
function foo () {     var a = 3,          = 2;      return A +b;} var c =//5
That is, the following code console.log to get the result of the function foo, just call the function to get the value a+b it returns. But if Foo is an async function, can you do that? definition of an asynchronous function: First of all, how to write asynchronous functions in JavaScript. The basic approach is to invoke the asynchronous API (either native or third-party) that someone else has provided in your function definition, and your function is an asynchronous function:
function Foo (callback) {     your own code;     ASYNCFN (function() {          var result = your own code;          Callback (result);     });}

In the above example, you define a function foo, which calls an asynchronous function ASYNCFN, and calls the callback function callback of Foo after ASYNCFN is run, to process the result. The above is the definition format for general asynchronous functions. SetTimeout is a common asynchronous API used in JavaScript. It is often used to simulate asynchronous operations when doing experiments, and the following example simulates an operation that will run for 1 seconds before returning the result (you can, of course, set 0 seconds, but it is still asynchronous):
function Foo (callback) {     your own code;     SetTimeout (function() {          var result = your own code;          Callback (result);      );}
In node. js, there are other APIs to play a similar role (write your sync code as an async function), setimmediate or Process.nexttick, which is the function of calling your code asynchronously. These two basically use similar, but the specific case is different, can find Setimmediate,settimeout (FN, 0) and Process.nexttick of the difference, generally do not understand the case, it is recommended to use Setimmediate.
function Foo (callback) {     your own code;     Setimmediate (function() {          var result = your own code;          Callback (result);      function Foo (callback) {     your own code;     Process.nexttick (function() {          var result = your own code;          Callback (result);     });}

Invocation of an asynchronous function:

The above is the definition of an asynchronous function, the following is how the asynchronous function is called. When invoking an asynchronous function, the callback function is written in two ways, one is to write an anonymous callback function directly, and in the following example, the function (data) {...} is an anonymous fallback:
Foo (data) {     Your code is used to send back the data;});
The second is to define a function and then use the function reference as the callback:
function Bar (data) {     Your code is used to send back the data;} Foo (bar);
Now back to the beginning of the question, some students must understand why the Async function cannot return the value. The following two types of writing together, easy to compare: correct wording:
function Foo (callback) {     your own code;     ASYNCFN (function() {          var result = your own code;          Callback (result);     });}
Error wording:
function Bar () {     your own code;     ASYNCFN (function() {          var result = your own code;     });           return result;}
In the wrong notation, bar attempts to return result using return. As already mentioned in the previous article, the asynchronous API will not wait for execution and then execute, that is, ASYNCFN immediately after the call will execute the return result of the sentence, this time ASYNCFN still in the asynchronous execution, the result is not calculated at all, So you can't return the desired result. Of course, the more familiar JavaScript syntax is also clear that the function outside the function can not access the internal variables, that is, the outside of the ASYNCFN function is inaccessible to the result of the variable, regardless of that is the main reason, which is secondary, The Async API is definitely not able to return a value with return. The above is the definition and invocation of basic asynchronous functions. Asynchronous Function Instances:Any tutorial that only speaks of theory and does not speak of application is bullying ... Well, here's a practical example: network requests are a common use in the node. JS asynchronous API, and there are a lot of node. JS native and third-party APIs that can make network requests, as shown in superagent for example (installing superagent with NPM before running):
 var  agent = require (' superagent ' ); Agent.get ( ' http://www.baidu.com ' ). End ( function   (err, res) {  (Err) {Console.log (err);  else   {Console.log ( ' http               Status: ' +
The above code can be run directly. In this example Agent.get (URL). End (callback) is an asynchronous API call that defines its own code in a callback function. The return function returns two data, err and res. If it doesn't, the Res object is the content of the full HTTP response, and if an error occurs, the error message is saved in the Err object. Here in order to demonstrate just the status and header of the res that is printed back in the console (note: superagent is a good HTTP client, you can go to GitHub to understand the specific features it provides). Incidentally, async functions cannot catch exceptions with try...catch like synchronous code, so there is a rule that there are two parameters to return a function, the above superagent example is err and res, the first parameter is error, When an asynchronous code has an exception with this parameter to return the exception details, the second parameter is the useful data returned, when there is no exception to use it to return, that is, the superagent example of RES, the return is the HTTP response content. Asynchronous Nesting:In the synchronous code, if there are three functions executed sequentially, the previous output as the last input, as long as the three functions are executed sequentially. But in async code, it's a bit of a hassle to do this. The reason for this is that because you cannot return a value as a synchronous function with return, you must use the back function. So, the second function is called in the callback of the first function, and the third function is called in the callback of the second function, which is called a callback nesting. The following example is to read its contents from A.txt, then read its contents from B.txt, and finally merge two content into Ab.txt, after which the console prints: Read and write done!
var fs = require (' FS '); fs.readfile(function(ERR1, data1) {     fs.readfile (  function(ERR2, data2) {          fs.writefile (function(err) {               console.log (' Read and write done! ' );          });     });});
Three asynchronous function nesting looks pretty straightforward. Imagine if there were 5, 10 or more asynchronous functions to be executed sequentially, how many layers would be nested? (People do not like the length of the body long bar haha) to tell the truth is quite scary, the code will become extremely difficult to read, difficult to debug, difficult to maintain. This is called the callback Hell or callback hell. It is in order to solve this problem, only the following two sectionto, with the Promise or generator asynchronous process management. Asynchronous process Management It's just to solve the problem of callback hell. So there are two sides to everything, asynchronous programming has its unique advantages, but also encountered a synchronous programming at the same time there is no code organization problem. Study Questions:Write your own asynchronous function there is also a common situation, that is, in the loop, such as the continuous invocation of the asynchronous function ASYNCFN, because each loop call ASYNCFN you do not know it will run to when, in this case, when your Foo function call back function to return the final result? You can experiment with read-write files, use the Fs.readfile function to iterate through the contents of all the files under a directory, and then use Fs.writefile to write to a new file. Answer tell:)
function foo (arr, callback) {     for(var i=0; i<arr.length; + +i) {          asyncfn (   function() {               your code;          }}     }}

Previous: JavaScript asynchronous programming one of the principles of asynchronous

Reprint please indicate source: http://www.cnblogs.com/chrischjh/p/4667713.html

Two callback functions for JavaScript asynchronous 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.