Problems and Solutions encountered

Source: Internet
Author: User

Future problems and solutions will be updated here.

May 1 1. How to implement Async
    • callback function
    • Event Monitoring
    • Publish/Subscribe
    • Promise Object
2.Promise and ES6 Generator

Promise is proposed to solve multiple callback function nesting. It's not hard to imagine that multiple nesting occurs when multiple files are read sequentially. Code is not vertical development, but horizontal development, will soon be mess, unable to manage. This is called a "callback function Nightmare" (Callback Hell). It is not a new syntax function, but a new way of writing, allowing the lateral loading of callback functions to be vertically loaded. Using promise, read multiple files continuously, the following is the wording.

var readFile = require (' fs-readfile-promise '); ReadFile (FileA). Then (function(data) {  Console.log (data.tostring ());}). Then (function() {  return  readFile (Fileb);}). Then (function(data) {  Console.log (data.tostring ());}). Catch (function(err) {  console.log (err);});

In the above code, the Fs-readfile-promise module is used, and its function is to return a promise version of the ReadFile function. Promise provides the then method to load the callback function, and the catch method catches the error thrown during execution.

The Generator function is the implementation of the ES6, and the most important feature is that it can hand over the execution of the function (i.e., suspend execution).

function* Gen (x) {  var y = yield x + 2;   return y;}

The above code is a Generator function. Unlike normal functions, it can be paused, so the function name should be preceded by an asterisk to show the difference.

The entire Generator function is a encapsulated asynchronous task, or a container for an asynchronous task. The place where the asynchronous operation needs to be paused is indicated by the yield statement. The Generator function is executed as follows.

var g = Gen (1//  {value:3, done:false}//  {value:undefined, do Ne:true}

In the above code, calling the Generator function returns an internal pointer (that is, the Walker) G. This is another place where the Generator function differs from the normal function, that is, executing it does not return a result, it returns a pointer object. Invoking the next method of the pointer G moves the internal pointer (that is, the first segment of the asynchronous task), pointing to the yield statement that was encountered first, and the previous example is performed to X + 2.

In other words, the next method functions as a phased execution of the Generator function. Each time the next method is called, an object is returned that represents the information for the current stage (the Value property and the Done property). The Value property is the expression following the yield statement, which represents the value of the current stage; The Done property is a Boolean value that indicates whether the Generator function is finished, that is, whether there is a next stage.

May 2 1. Execution mechanism of JS asynchronous task

(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).

(2) In addition to the main thread, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.

(3) Once all the synchronization tasks in the "execution stack" have been executed, the system reads the "task queue" to see what events are in it. Those corresponding asynchronous tasks, so end the wait state, go to the execution stack, and start execution.

(4) The main thread constantly repeats the third step above.

2. The execution mechanism of the timer

The timer function is mainly by settimeout () and setinterval () These two functions to complete, their internal operation mechanism is exactly the same, the difference is that the former specified code is one-time execution, the latter is repeated execution. The following main discussion settimeout ().

SetTimeout () accepts two parameters, the first is a callback function, and the second is the number of milliseconds to defer execution.

Console.log (1); SetTimeout (function() {console.log (2);},1000); Console.log (3);

The result of the above code is 1,3,2, because settimeout () defers the second line to 1000 milliseconds after execution.

If you set the second parameter of settimeout () to 0, the callback function specified immediately (0 millisecond interval) is executed as soon as the current code finishes executing (execution stack emptying).

SetTimeout (function() {console.log (1);}, 0); Console.log (2);

The result of the above code is always 2,1, because only after the second line is executed will the system execute the callback function in the task queue.

In summary, setTimeout (fn,0) means that a task is specified to execute at the earliest available idle time of the main thread, that is, to execute as early as possible. It adds an event at the end of the task queue, so it will not be executed until both the synchronization task and the task queue existing events are processed.

The HTML5 standard specifies the minimum value (minimum interval) of the second parameter of the settimeout (), which is not less than 4 milliseconds, and is automatically incremented if it is below this value. Prior to this, the older versions of the browser set the minimum interval to 10 milliseconds. In addition, the changes to those dom, especially those involving page re-rendering, are usually not executed immediately, but once every 16 milliseconds. The effect of using requestanimationframe () is better than settimeout ().

It is important to note that setTimeout () simply inserts the event into the "task queue" and must wait until the current code (execution stack) finishes executing, before the main thread executes the callback function it specifies. If the current code takes a long time, it may take a long time, so there is no guarantee that the callback function will be executed at settimeout ().

Problems and Solutions encountered

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.