- 需要所有介面載入完畢後再進行處理事情
- 需要優化多個 http/IO 介面巢狀導致效能變慢
- 需要多個任務完成後再進行處理回撥
function pail(len) {
return {
len: len,
num: 0,
t_fun: null,
c_fun: null,
then: function (fun) {
this.t_fun = fun;
return this;
},
catch: function (fun) {
this.c_fun = fun;
return this;
},
pass: function () {
this.num += 1;
if (this.num >= this.len) {
if (this.t_fun) {
this.t_fun(this)
}
}
},
fail: function () {
if (this.c_fun) {
this.c_fun(this)
}
},
is_pass: function () {
return this.num >= this.len;
}
}
}
function pail2(len) {
return {
len: len,
num: 0,
data: {},
t_fun: null,
c_fun: null,
then: function (fun) {
this.t_fun = fun;
return this;
},
catch: function (fun) {
this.c_fun = fun;
return this;
},
push: function (key, value) {
this.data[key] = value;
this.pass();
},
pass: function () {
this.num += 1;
if (this.num >= this.len) {
if (this.t_fun) {
this.t_fun(this)
}
}
},
fail: function () {
if (this.c_fun) {
this.c_fun(this)
}
},
is_pass: function () {
return this.num >= this.len;
}
}
}
function pail3(len) {
return {
len: len,
num: 0,
data: [],
t_fun: null,
c_fun: null,
then: function (fun) {
this.t_fun = fun;
return this;
},
catch: function (fun) {
this.c_fun = fun;
return this;
},
push: function (value) {
this.data.push(value);
this.pass();
},
pass: function () {
this.num += 1;
if (this.num >= this.len) {
if (this.t_fun) {
this.t_fun(this)
}
}
},
fail: function () {
if (this.c_fun) {
this.c_fun(this)
}
},
is_pass: function () {
return this.num >= this.len;
}
}
}
let c = pail2(2);
c.then(r => {
console.log("全部載入成功後要乾的事情", r.data)
})
.catch(e => {
console.log("載入失敗後乾的事情")
})
setTimeout(function() {
if(true) {
c.push("user", {name:"張三", sex: "男"})
} else {
c.error()
}
}, 1000)
setTimeout(function() {
if(true) {
c.push("money", {amount: 0.12})
} else {
c.error()
}
}, 1000)
本作品採用《CC 協議》,轉載必須註明作者和本文連結