Asynchronous sorting in JavaScript (1) -- message-driven

Source: Internet
Author: User

For example, if you want the five functions ABCDE to be executed in sequence, you can write the following code.

A();B();C();D();E();

 

In the case of synchronization, such code has no problems. However, if ABCDE is asynchronous, it still needs to be executed in order, so it won't work. We usually set a callback for the asynchronous function, and execute the callback when the function is executed, for example

A(function(){    B(function(){        C(function(){            D(function(){                E();            });        });    });});

There is no doubt that such a programming experience is poor. When asynchronous streams are complex, there will be many layers of nested callback, which is a nightmare.

This is not the most important thing. If you want to express A process like "execute C When AB completes" and want A/B To be parallel, you cannot simply use this callback.
Although "execute C When AB is complete" can be solved by setting a Boolean value, however, the logic "execute E when ABCD is complete" needs to judge whether other functions are executed when each function is executed. Although it is indeed feasible, however, programming is poor.

As a lazy programmer, this obviously cannot satisfy our appetite.

@ Poling wrote an EventProxy that provides an event-driven asynchronous programming experience.

var proxy = new EventProxy();proxy.assign('A', function(){    B(function(){        proxy.trigger('B');    });});proxy.assign('B', function(){    C(function(){        proxy.trigger('C');    });});proxy.assign('C', function(){    D(function(){        proxy.trigger('D');    });});proxy.assign('D', function(){    E();});A(function(){    proxy.trigger('A');});

It can be seen that the Code driven by messages can be flattened by asynchronous nesting, and it is easy to describe the process "execute E when ABCD is complete ".

 

var proxy = new EventProxy();proxy.assign('A', 'B', 'C', 'D', E);A(function(){    proxy.trigger('A');});B(function(){    proxy.trigger('B');});C(function(){    proxy.trigger('C');});D(function(){    proxy.trigger('D');});

In addition to improving the asynchronous programming experience, EventProxy can also provide a Custom Event System.

EventProxy is very simple. The source code is only over 300 lines, but for mobile developers like me, any code that cannot be used is a burden.
Because I split the Event system into a separate module, and I (so far) do not need the function of passing parameters when EventProxy triggers a message. For some, any, I don't need these restrictions, so I implemented a simple version of asynchronous traffic control tool.

(function(export){var uid = 1;var Jas = function(){    this.map = {};    this.rmap = {};};var indexOf = Array.prototype.indexOf || function(obj){    for (var i=0, len=this.length; i<len; ++i){        if (this[i] === obj) return i;    }    return -1;};var fire = function(callback, thisObj){    setTimeout(function(){        callback.call(thisObj);    }, 0);};Jas.prototype = {    waitFor: function(resources, callback, thisObj){        var map = this.map, rmap = this.rmap;        if (typeof resources === 'string') resources = [resources];        var id = (uid++).toString(16); // using hex        map[id] = {            waiting: resources.slice(0), // clone Array            callback: callback,            thisObj: thisObj        };         for (var i=0, len=resources.length; i<len; ++i){            var res = resources[i],                list = rmap[res] || (rmap[res] = []);            list.push(id);        }        return this;    },    trigger: function(resources){        if (!resources) return this;        var map = this.map, rmap = this.rmap;        if (typeof resources === 'string') resources = [resources];        for (var i=0, len=resources.length; i<len; ++i){            var res = resources[i];            if (typeof rmap[res] === 'undefined') continue;            this._release(res, rmap[res]); // notify each callback waiting for this resource            delete rmap[res]; // release this resource        }        return this;    },    _release: function(res, list){        var map = this.map, rmap = this.rmap;        for (var i=0, len=list.length; i<len; ++i){            var uid = list[i], mapItem = map[uid], waiting = mapItem.waiting,                pos = indexOf.call(waiting, res);            waiting.splice(pos, 1); // remove            if (waiting.length === 0){ // no more depends                fire(mapItem.callback, mapItem.thisObj); // fire the callback asynchronously                delete map[uid];            }        }    }};export.Jas = Jas; // Jas is JavaScript Asynchronous (callings) Synchronizer})(window);

Easy to use

var flow = new Jas();flow.waitFor(['A', 'B'], function(){    // both A and B are done!!}); $.getJSON(url1, function(data){    // An ajax request    flow.trigger('A');});$.getJSON(url2', function(data){    // Another ajax request    flow.trigger('B');});

Summary:
The message-driven approach allows us to avoid some callback nesting nightmares in asynchronous programming, optimize programming experience, and make the process more flexible when there are modifications, you can describe the asynchronous function stream in a way similar to the "Declaration" type.

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.