RPM: Promises and JavaScript asynchronous programming

Source: Internet
Author: User

Ajax applications are truly ubiquitous in an era of user experience today. With the development of browser technology, HTML5, CSS3 and so on, more and more rich Web applications appear, while the Web developers need to deal with more and more asynchronous callback logic in the background while giving us a good experience.

The author of the recent reading of the "async javascript-build more responsive apps with less code" (Javascript asynchronous programming-design of fast-response Web applications) and some of the information, I've sorted out some of the more important points and things that are easy to understand, giving you a deeper understanding of promise objects and asynchronous programming.

Nested callbacks
    1. SetTimeout (function () {
    2. SetTimeout (function () {
    3. Do something
    4. }, 10)
    5. }, 100);
    6. $.ajax (URL, function () {
    7. $.ajax (Url2, function () {
    8. $.ajax (Url3, function () {
    9. Do something
    10. });
    11. });
    12. });

The problem, however, is that the more nested we are, the more deeply the code hierarchy becomes. First, it becomes difficult to read, followed by strong coupling, and the interface becomes poorly expanded. We need a pattern to solve this problem, and that's what promises is going to do.

Asynchronous function type

The asynchronous functions in JavaScript can be divided into two main types:

    • I/O functions (Ajax, Script ... )
    • Timing Functions (SetTimeout, setinterval, Setimmediate)
Asynchronous function Exception capture
    1. try {
    2. SetTimeout (function A () {
    3. SetTimeout (function B () {
    4. SetTimeout (function C () {
    5. throw new error (' Error ');
    6. }, 0);
    7. }, 0);
    8. }, 0);
    9. } catch (e) {}

Run the above code, a, B, C is added to the event queue; When the exception is triggered, A, B has been moved out of the event queue, only C in the memory stack, when the exception is not caught by the try, only flow to the application does not catch the exception handler.

Therefore, in an async function, you cannot use Try/catch to catch exceptions.

Distributed events

The event core of JavaScript is the event distribution mechanism, which achieves asynchronous response by binding a subscription handle to the Publisher:

    1. Document.onclick = function () {
    2. Click
    3. };

PubSub (Publish/subscribe, publish/subscribe) mode is a pattern that achieves multi-tier distribution decoupling by subscribing to the publisher's event response.

The following is a simple version of the pubsub pattern implementation:

  1. var PubSub = (function () {
  2. var _handlers = {};
  3. return {
  4. Subscribe to Events
  5. On:function (EventType, handler) {
  6. if (!_handlers[eventtype]) {
  7. _handlers[eventtype] = [];
  8. }
  9. if (typeof handler = = ' function ') {
  10. _handlers[eventtype].push (handler);
  11. }
  12. },
  13. Publish Events
  14. Emit:function (EventType) {
  15. var args = Array.prototype.slice.call (arguments, 1);
  16. var handlers = _handlers[eventtype] | | [];
  17. for (var i = 0, len = handlers.length; i < Len; i++) {
  18. Handlers[i].apply (null, args)
  19. }
  20. }
  21. };
  22. })();
PROMISES/A specification

COMMONJS's PROMISES/A specification was proposed by Kris Zyp in 2009, which simplifies asynchronous programming by standardizing API interfaces, making our asynchronous logic code easier to understand.

Following the implementation of the PROMISES/A specification we call the Promise object, Promise object has only three states: unfulfilled (not completed), fulfilled (completed), failed (failed/rejected) And the state changes can only be from unfulfilled to fulfilled, or unfulfilled to failed;

The Promise object needs to implement a then interface, then(Fulfilledhandler, ErrorHandler, Progresshandler), and then the interface receives a successful callback ( Fulfilledhandler) with a failed callback (ErrorHandler), Progresshandler Trigger callback is optional and the Promise object does not force a callback to this handle.

Then the implementation of the method needs to return a new Promise object to form a chained call, or a promise pipeline.

To achieve a state transition, we also need to implement two additional interfaces:

    • Resolve: Implementation status from unfinished to completed
    • Reject: implementation state from incomplete to rejected (failed)

In this way, the nested callback we're talking about here can be written like this:

  1. This assumes that promise is an implemented promise object
  2. function AsyncFn1 () {
  3. var p = new Promise ();
  4. SetTimeout (function () {
  5. Console.log (1);
  6. P.resolve (); Mark as Completed
  7. }, 2000);
  8. return p;
  9. }
  10. function AsyncFn2 () {
  11. var p = new Promise ();
  12. SetTimeout (function () {
  13. Console.log (2);
  14. P.reject (' error '); Mark as rejected
  15. }, 1000);
  16. return p;
  17. }
  18. ASYNCFN1 ()
  19. . then (function () {
  20. return asyncFn2 ();
  21. }). Then (function () {
  22. Console.log (' done ');
  23. }, function (err) {
  24. Console.log (ERR);
  25. });

With promise, we can write asynchronous logic with a synchronized mind. In the world of synchronization functions, there are 2 very important concepts:

    • has a return value
    • can throw an exception

Promise is not only a kind of object that can be called by chain, but also provides a more direct correspondence between asynchronous function and synchronous function.

As we said above, in an async function, you cannot use Try/catch to catch an exception, so you cannot throw an exception. With promise, as long as we explicitly define the ErrorHandler, then we can do the same as the synchronous function of the exception capture.

Go: Promises and JavaScript asynchronous programming

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.