Asynchronous Programming When.js

Source: Internet
Author: User

When.js is very small, after compression only a few kb,gzip after the size can almost be ignored. When.js can be used in both node and browser environments

First, let's look at a short piece of code:

var getData =function(callback) {$.getjson (API,function(data) {Callback (data[0]); });} var getimg = function (SRC, callback) {var img = new Image (); Img.onload = function () { Callback (IMG); }; IMG.SRC = src;} var showimg = function ' #container '));} GetData (function (data) {GETIMG (Data, function (IMG) {SHOWIMG ( IMG); });}); 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25

This code completes three tasks: 1) Get the data, 2) load the image, 3) display the picture, where tasks 1 and 2 are asynchronous, 3 is synchronous, using the most common callback mechanism to handle asynchronous logic, the benefits are easy to understand, the disadvantage is strong coupling, not intuitive, handling the exception of trouble and so on.

We're trying to rewrite this code with When.js:

var getData =function() {var deferred = When.defer (); $.getjson (API,function0]); return deferred.promise;} var getimg = function (SRC) {var deferred = When.defer (); var img = new Image (); img.onload = function () {Deferred.resolve ( IMG); }; IMG.SRC = src; return deferred.promise;} var showimg = function ' #container '));} GetData (). Then (getimg). then (showimg);             
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

See the last three lines of code, is not at a glance, very semantic? Look at the rewritten task 1 and 2 more:

var deferred = when.defer();
    • 1

Defines a deferred object.

deferred.resolve(data);
    • 1

When the asynchronous fetch data is complete, the data is used as a parameter to invoke the Resolve method of the deferred object.

return deferred.promise;
    • 1

Returns the Promise property of the deferred object.
In the PROMISES/A specification, there are three states for each task: default (Pending), complete (fulfilled), failure (rejected).

    • The default state can be transferred one way to the completion state, this process is called resolve, the corresponding method is Deferred.resolve (Promiseorvalue);
    • The default state can also be transferred one-way to the failed state, the process is called reject, the corresponding method is deferred.reject (reason);
    • By default, task execution information, such as execution progress, can also be declared through Deferred.notify (update).
    • The transition of the state is one-time, and once the task is moved from the initial pending to the other State, it goes into the next task execution.

One might find it strange that the resolve and reject methods that change the state of the task are defined on the deferred object, but the Promise property of the deferred is finally returned. This is done because the specification is so set, and the second is to prevent the task State from being externally altered.
Then there are three parameters, namely onfulfilled, onrejected, OnProgress, and with these three parameters, you can specify what to do with the previous task at resolve, reject, and notify. For example, the previous task is resolve (data), onfulfilled function will be triggered, data as its parameters; reject (reason), then onrejected will be triggered, received reason. At any time, onfulfilled and onrejected can only be triggered and triggered only once, and OnProgress is called every time the Notify, as the name implies. Here are the uses of reject and notify:

functionRun() {var deferred = When.defer ();var start =1, end = 100; (function () {if (start <= end) {deferred.notify (start++); SetTimeout (50); } else {deferred.reject ( ' time out! ');}}) (); return deferred.promise;} Run (). Then (undefined,  Function function (s) {document.getElementById (  '% ';});      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23

Then the error is passed, that is, when multiple tasks are executed serially, we can define the onrejected only at the last then. Only the then onrejected is defined as otherwise, which means that otherwise (onrejected) is the easy way to do so (undefined, onrejected).
Then it will be in try. Catch.. Package, the task's exceptions are captured by When.js and treated as a failed state, similar to this:

try {    ...} catch (e) {    deferred.reject(e);}
    • 1
    • 2
    • 3
    • 4
    • 5

After the task status changes and then, still can work normally, the successor task will execute immediately. If you want to do cleanup work at the end of multiple tasks, regardless of whether the previous task succeeds or not, you can use the ensure method. It accepts only one parameter onfulfilledorrejected, which is always executed. In addition When.js has a always method, will be discarded, we recommend not to use.
Back to the scene where the picture is loaded, if you change task 2 to: Load multiple pictures, complete and then perform task 3. At this point, we need to use When.all,when.all to accept an promise array, return promise, this promise promise in promise array resolve after each resolve. Speaking of a mouthful, look at the code to understand:

var getData =function() {var deferred = When.defer (); $.getjson (API,function(data) {var data = Data.slice (0,3); Deferred.resolve (data); });return deferred.promise;}var getimg =function(SRC) {var deferred = When.defer ();var img =New Image (); Img.onload =function () {Deferred.resolve ( IMG); }; IMG.SRC = src; return deferred.promise;} var Showimgs = function ' #container '));} var Getimgs = functionvar deferreds = []; for (var i = 0; I < Data.length; i++) {Deferreds.push (getimg (Data[i]));} return deferreds;} When.all (GetData (). Then (Getimgs)). then (Showimgs);           
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

If we just want to execute a promise array one at a time, we can use When.settle:

var promise1 =function() {var deferred = When.defer (); SetTimeout (function() {Deferred.reject (' A '); },2000);return deferred.promise;}; var promise2 =function () {var deferred = When.defer (); SetTimeout (function () { Deferred.resolve ( ' B '), 2000); return deferred.promise;}; When.settle ([Promise1 (), Promise2 ()]). then (function " rejected ", " reason ": " A "}, {  "fulfilled",  "value": Span class= "hljs-string" > "B"}] */});             
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st

Sometimes, we need to introduce a task-based competition mechanism, such as finding the fastest one from a batch of CDNs, When.any comes in handy, When.any accepts promise arrays, and then performs subsequent tasks after any one of the resolve. If you want to perform subsequent tasks after a few resolve in a batch of promise, you can use When.some, which is one more howmany parameter than When.any.
Promise to the asynchronous programming code to bring great convenience, since then we can focus on the implementation of a single task, promise will be good for us to solve the task scheduling problem. When.js offers much more than these, and interested students can go to the official API documentation to learn more.

Github:https://github.com/cujojs/when#legacy-environments
Via:jerry Qu
This article link: https://imququ.com/post/promises-when-js.html

Asynchronous Programming When.js

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.