标签:end function state 编程 led 回调 err progress console
Promise三种状态:未完成、完成态、失败态
var events = require(‘events‘); var util = require(‘util‘); var EventEmitter = events.EventEmitter; var Promise = function () { EventEmitter.call(this); } util.inherits(Promise, EventEmitter); Promise.prototype.then = function (fulfilledHandler, errorHandler, progressHandler) { if (typeof fulfilledHandler === ‘function‘) { //利用once()方法,保证成功回调执行一次 this.once(‘success‘, fulfilledHandler) } if (typeof errorHandler === ‘function‘) { //利用once()方法,保证异常回调执行一次 this.once(error, errorHandler) } if (typeof progressHandler === ‘function‘) { this.on(‘progress‘, progressHandler) } return this; }
这里看到then方法就是将回调存放起来,为了完成整改流程,还需要触发回调函数的地方,实现这些函数的对象叫Deferred,即延迟对象
var Deferred = function () { this.state = ‘unfulfilled‘; this.promise = new Promise(); } Deferred.prototype.resove = function (obj) { this.state = ‘fulfilled‘; this.promise.emit(‘success‘, obj); } Deferred.prototype.error = function (obj) { this.state = ‘failed‘; this.promise.emit(‘fail‘, obj); } Deferred.prototype.progress = function (data) { this.promise.emit(‘progress‘, data); }
利用promise/A模式,我可以对典型的响应对象进行封装,代码如下:
res.setEncoding(‘utf8‘) res.on(‘data‘, function (chunk){ console.log(chunk); }) res.on(‘end‘, function (){ console.log(‘end‘) }) res.on(‘error‘, function (err) { console.log(‘err‘); }) res.writeHead(‘200‘, {contentType: ‘text/plain‘}); res.end(‘练习一下: promise test‘);
标签:end function state 编程 led 回调 err progress console
原文地址:https://www.cnblogs.com/yingquliang/p/9375034.html