对之前写的promise介绍进行补充,借助有限状态机来将状态对象和主题对象进行分离,对状体的变化逻辑进行单独处理。
环境配置
首先需要安装babel及babel插件,解析ES6语法
安装后在.babelrc中输入以下内容
{
"presets": ["es2015", "latest"],
"plugins": ["transform-decorators-legacy"]
}
该简单实现中使用了javascript-state-machine第三方库,也需要进行安装
具体实现代码
import StateMachine from "javascript-state-machine";
// 状态机模型
let fsm = new StateMachine({
init: "pending",
transitions: [
{ name: "resolve", from: "pending", to: "fulfilled" },
{
name: "reject",
from: "pending",
to: "rejected"
}
],
methods: {
onResolve: function(state, data) {
// state - 当前状态机实例,data - fsm.resolve(xxx)
data.successList.forEach(fn=>fn())
},
onReject: function(state, data) {
data.failList.forEach(fn=>fn())
}
}
});
// 定义Promise
class MyPromise {
constructor(fn) {
this.sucessList = []
this.failList = []
fn(
function() {
// resolve函数
fsm.resolve(this)
},
function() {
// reject函数
fsm.reject(this)
}
);
then(successFn, failFn){
this.successList.push(successFn)
this.failList.push(failFn)
}
}
}
// 测试代码
function loadImg(src) {
const promise = new Promise(function(resolve, reject) {
let img = document.createElement("img");
img.onload = function() {
resolve(img);
};
img.onerror = function() {
reject();
};
img.src = src;
});
return promise;
}
let src
let result = loadImg(src)
result.then(function(){
console.log('ok1')
}, function () {
console.log('fail1')
})
result.then(function () {
console.log('ok2')
}, function () {
console.log('fail2')
})
网友评论