Explore JavaScript Asynchronous Programming

Source: Internet
Author: User
Tags readfile

In our daily coding, there are many scenarios that need to be asynchronous, such as reading file contents, acquiring remote data, sending data to the server, etc. Because the browser environment Javascript is single-threaded, asynchronous programming is particularly important in the front-end domain.

The concept of async

The so-called asynchronous means that when a procedure call is issued, the caller cannot get the result immediately. The process of actually processing the call notifies the caller by status, notification, or callback after completion.

For example, when we write this text click the Publish button, we can not immediately get the article publish success or failure. Wait for the server to process, this time we can do other things, when the server processing is completed, notify us whether the release is successful.

The so-called synchronization, when a process call is issued, must wait for the process to finish processing, and then handle other things. That is, blocking execution.

Asynchronous Way

es6before, we implemented async in 4 ways, callbacks, events, publish subscriptions, and promise.

Asynchronous callbacks:
function dealTask(param, callback) {    // Deal with some time consuming tasks. // ... Object.prototype.toString.call(callback) === ‘[object Function]‘ ? callback() : null; } dealTask({ id: 1 }, function() { console.log(‘... I am in the callback...‘);})

Callback is the way to implement the asynchronous function is the need to execute after the current task is passed as a parameter, the completion of the task after the execution.

Asynchronous events
function dealTask(param) {    // Deal with some time consuming tasks. // ... events.trigger(‘dealTaskFinish‘)}events.on(‘dealTaskFinish‘, function() { console.log(‘...I am in the end...‘);})

The benefits of implementing callbacks through events are convenient and practical, passing data across modules. The downside is that the event used more after the business logic confusion, do not know where to register where to listen.

It is also important to note that in the web component scenario, the mount post-registration event needs to be unmount released, otherwise it will cause a memory leak.

Asynchronous Publish Subscription

A simple example of a publish subscription is a switch that simultaneously switches several bulbs in parallel (in different rooms), and when triggered, a few bulbs are given instructions and then perform the glowing behavior.

// 使用pubsubz实现var testSubscriber = function(data ){ console.log(data );};var testSubscription = pubsubz.subscribe( ‘example‘, testSubscriber );pubsubz.publish( ‘example‘, ‘hello‘ );

The nature of subscription publishing is similar to "event snooping", where we can monitor the operation of a program by looking at the message center to see how many signals exist, how many subscribers each signal has.

The promise of Asynchrony
functionhelloworld (ready) {return new promise ( function (resolve, reject) {if ( Ready) {Resolve ( "Hello world!")} else {reject ( "good bye!")}})} HelloWorld (true). Then ( function (message) {console.log (Message)}, function (error) { console.log (Error)})           

Promises object is a kind of specification that COMMONJS Working group puts forward, it is a kind of unification to asynchronous programming, in fact is the grammatical sugar, the readable sex becomes stronger only.

After the ES6 came out, our asynchronous approach also changed.

The generator of Asynchrony

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).

The generator function can pause execution and resume execution, which is the root cause of its ability to encapsulate asynchronous tasks. In addition, it has two features that allow it to act as a complete solution for asynchronous programming: data exchange and error handling mechanisms outside the body of the function.

function* Foo(x) {  yield x + 1; var y = yield null; return x + y;}var foo = Foo(5);foo.next(); // { value: 6, done: false }foo.next(); // { value: null, done: false }foo.next(8); // { value: 13, done: true }

The next method returns the Value property of the generator function, and the next method can also accept the parameter, which is to enter data into the generator function body.

The yield command is used to move the execution of the program out of the generator function, then a method is needed to return the execution to the generator function

The above approach is that we call generator function execution manually, but when we need to execute the next method a lot, we need the generator function to execute automatically.

The automatic execution of the generator function means that the next method is automatically executed in a certain way, such as:

function autoRunGen(gen){  var g = gen();  function next(data){ var result = g.next(data); if (result.done) return result.value; result.value.then(function(data){ next(data); }); } next();}

The Co module is a small tool developed by TJ for automating the execution of generator functions. His main idea is similar to the code snippet above.

The precondition for using CO is that the yield command of the generator function is followed by the Promise object only.

co(function *() {    var data = yield $.get(‘/api/data‘); console.log(data); var user = yield $.get(‘/api/user‘); console.log(user); var products = yield $.get(‘/api/products‘); console.log(products);});

The Co module allows us to write asynchronous code just like the synchronous code.

The async/await of Asynchrony

The async function is simply the syntactic sugar of the generator function.

var fs =Require' FS ');var readFile =function (FileName) {ReturnNewpromise (function (resolve, Reject) {Fs.readfile (fileName,  function (error, data) {if (Error) reject (error); Resolve (data) ; }); });}; var gen = function* (var f1 = yield readFile ( /etc/a.js '); var F2 = yield readFile (/etc/b.js ‘); console.log (f1.tostring ()); console.log (f2.tostring ());          

How to use async/await :

var asyncReadFile = async function (){ var f1 = await readFile(‘/etc/a.js‘); var f2 = await readFile(‘/etc/b.js‘); console.log(f1.toString()); console.log(f2.toString());};

The async function replaces the asterisk (*) of the generator function with async, replacing yield with await, which is all.

The difference is that generator execution needs to be performed manually, and async functions can be executed automatically, like write synchronization. Generator returns the Iterator object, and the Async function returns the Promise object.

Explore 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.