偽代碼
class my_promise {
? constructor(fun) {
? ? const that = this;
? ? this._queue = []; // 隊列
? ? that._success_res = null;
? ? that._error_res = null;
? ? that.status = "";// 狀態(tài)機
? ? fun(
? ? ? (...args) => {
? ? ? ? that._success_res = args;
? ? ? ? that.status = "success";
? ? ? ? that._queue.forEach(json => {
? ? ? ? ? json.fun1(...args);
? ? ? ? });
? ? ? },
? ? ? (...args) => {
? ? ? ? that._error_res = args;
? ? ? ? that.status = "error";
? ? ? ? that._queue.forEach(json => {
? ? ? ? ? json.fun2(...args);
? ? ? ? });
? ? ? }
? ? );
? }
? then(fun1, fun2) {
? ? if (this.status === "success") {
? ? ? fun1(this._success_res);
? ? } else if (this.status === "error") {
? ? ? fun2(this._error_res);
? ? } else {
? ? ? // 異步操作還沒完
? ? ? this._queue.push({ fun1, fun2 });
? ? }
? }
}
my_promise.all = arr => {
? let list = [];
? return new my_promise((resolve, reject) => {
? ? let i = 0;
? ? next();
? ? function next() {
? ? ? arr[i].then(res => {
? ? ? ? list.push(res);
? ? ? ? i++;
? ? ? ? if (i === arr.length) {
? ? ? ? ? resolve(list);
? ? ? ? } else {
? ? ? ? ? next();
? ? ? ? }
? ? ? }, reject);
? ? }
? });
};