對之前寫的promise介紹進(jìn)行補(bǔ)充虱疏,借助有限狀態(tài)機(jī)來將狀態(tài)對象和主題對象進(jìn)行分離乌询,對狀體的變化邏輯進(jìn)行單獨(dú)處理背蟆。
環(huán)境配置
首先需要安裝babel及babel插件,解析ES6語法
安裝后在.babelrc中輸入以下內(nèi)容
{
"presets": ["es2015", "latest"],
"plugins": ["transform-decorators-legacy"]
}
該簡單實(shí)現(xiàn)中使用了javascript-state-machine第三方庫劣砍,也需要進(jìn)行安裝
具體實(shí)現(xiàn)代碼
import StateMachine from "javascript-state-machine";
// 狀態(tài)機(jī)模型
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 - 當(dāng)前狀態(tài)機(jī)實(shí)例惧蛹,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函數(shù)
fsm.resolve(this)
},
function() {
// reject函數(shù)
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')
})