javascript异步编程的实现方式

js的异步编程实现方法,常用的有以下四种方式:

1 回调函数 (callbacks) 

// setup

function finder(records, cb) {
    setTimeout(function () {
        records.push(3, 4);
        cb(records);
    }, 500);
}
function processor(records, cb) {
    setTimeout(function () {
        records.push(5, 6);
        cb(records);
    }, 500);
}

// using the callbacks
finder([1, 2], function (records) {
    processor(records, function(records) {
             console.log(records);       
    });
});

// or

function onProcessorDone(records){
    alert(records);   
}

function onFinderDone(records) {
    processor(records, onProcessorDone);
}

finder([1, 2], onFinderDone);

2 事件监听 (listeners)

// using listeners
var eventable = {
    on: function(event, cb) {
        $(this).on(event, cb);
    },
    trigger: function (event, args) {
        $(this).trigger(event, args);
    }
}
    
var finder = {
    run: function (records) {
            var self = this;
        setTimeout(function () {
            records.push(3, 4);
           self.trigger('done', [records]);            
        }, 500);
    }
}
var processor = {
    run: function (records) {
         var self = this;
        setTimeout(function () {
            records.push(5, 6);
            self.trigger('done', [records]);            
        }, 500);
    }
 }
 $.extend(finder, eventable);
 $.extend(processor, eventable);
    
finder.on('done', function (event, records) {
          processor.run(records);  
    });
processor.on('done', function (event, records) {
    alert(records);
});
finder.run([1,2]);

3  发布/订阅 (control flow libs)

4 Promise (promise ) 

function log(msg) {
    document.write(msg + '<br />');
}

// using promises
function finder(records){
    var deferred = when.defer();
    setTimeout(function () {
        records.push(3, 4);
        log('records found - resolving promise');
        deferred.resolve(records);
    }, 100);
    return deferred.promise;
}

var promise = finder([1,2]);

// wait 
setTimeout(function () {
    // when this is called the finder promise has already been resolved
    promise.then(function (records) {
        log('records received');        
    });
}, 1500);

出处:http://www.ruanyifeng.com/blog/2012/12/asynchronous_javascript.html

http://top.css88.com/archives/506

http://sporto.github.io/blog/2012/12/09/callbacks-listeners-promises/

https://github.com/caolan/async

https://github.com/cujojs/when

posted @ 2016-02-18 10:50  一渡  阅读(79)  评论(0)    收藏  举报