Promise/A模式相對比較簡單,主要適用於單個異步操作,具體如下:
- 只會存在三種狀態:未完成態、完成態和失敗態。
- 未完成態只能向完成態和失敗態轉化。完成態和失敗態不能相互轉化。
- 狀態一旦轉化,不能更改。
以文件讀取爲例
var fs = require("fs");
var path = require("path");
var readStream = fs.createReadStream(path.normalize('/test/1.txt'));
var fileContent = "";
readStream.on("error", function(err){
console.log(err);
})
readStream.on("data", function(data){
fileContent += data;
})
readStream.on("end", function(){
console.log("讀取完成");
console.log(fileContent.toString());
})
通過events模塊實現一個簡單的Promise/A。
Promise
var util = require("util");
var EventEmitter = require("events");
var Promise = function(){
EventEmitter.call(this);
}
util.inherits(Promise, EventEmitter)
Promise.prototype.then = function(successHandler, errorHandler, processHandler){
if(typeof successHandler === 'function'){
// 成功函數只執行一次
this.once('success', successHandler);
}
if(typeof errorHandler === 'function'){
// 失敗函數只執行一次
this.once('error', errorHandler)
}
if(typeof processHandler === 'function'){
this.on('process', processHandler)
}
}
Deffered
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.process = function(data){
this.promise.emit("process", data);
}
封裝
var deferred = function(readStream){
var defferred = new Deferred();
readStream.on("error",function(err){
defferred.reject(err)
})
readStream.on("end", function(){
defferred.resolve();
})
readStream.on("data", function(data){
defferred.process(data)
})
return defferred.promise;
}
var fileContent = ""
deferred(readStream).then(function(){
console.log(fileContent.toString());
}, function(err){
console.log(err);
}, function(data){
fileContent += data;
})