nodejsの中で簡単にJavascript Promiseの構造の実例を実現します.

2925 ワード

promise/deferredは、非同期呼び出しコードの仕様をうまく処理し、次はnodejsコードをクラスにして、promise/A仕様を簡単に実現します.
 
  
/**
 * Created with JetBrains WebStorm.
 * User: xuwenmin
 * Date: 14-4-1
 * Time: 9:54
 * To change this template use File | Settings | File Templates.
 */

var EventEmitter = require('events').EventEmitter;
var http = require('http');
var util = require('util');
// promise
var Promise = function(){
    //
    EventEmitter.call(this);
}
//
util.inherits(Promise, EventEmitter);
// then promise/A
Promise.prototype.then = function(successHandler, errorHandler, progressHandler){
    if (typeof successHandler == 'function'){
        this.once('success', successHandler);
    }
    if (typeof errorHandler === 'function'){
        this.once('error', errorHandler);
    }
    if (typeof progressHandler === 'function'){
        this.on('process', progressHandler);
    }
    return this;
}

//
// promise
var Deferred = function(){
    this.state = 'unfulfilled';
    this.promise = new Promise();
}
Deferred.prototype.resolve = function(obj){
    this.state = 'fulfilled';
    this.promise.emit('success', obj);
}
Deferred.prototype.reject = function(err){
    this.state = 'failed';
    this.promise.emit('error', err);
}
Deferred.prototype.progress = function(data){
    this.promise.emit('process', data);
}

// http promise/deferred

var client = function(){
    var options = {
        hostname:'www.baidu.com',
        port:80,
        path:'/',
        method: 'get'
    };
    var deferred = new Deferred();
    var req = http.request(options, function(res){
        res.setEncoding('utf-8');
        var data = '';
        res.on('data', function(chunk){
            data += chunk;
            deferred.progress(chunk);
        });
        res.on('end', function(){
            deferred.resolve(data);
        });
    });
    req.on('error', function(err){
        deferred.reject(err);
    })
    req.end();
    return deferred.promise;
}
client().then(function(data){
    console.log(' ', data);
}, function(err){
    console.log(' ', err);
}, function(chunk){
    console.log(' ', chunk);
});

コードはpromise.jsとして保存されています.コマンドラインの下で実行できます.直接node promise.jsを入力すれば、運行効果が見られます.