场景
- 需要所有接口加载完毕后再进行处理事情
- 需要优化多个 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)