Skip to content

Instantly share code, notes, and snippets.

@AJLoveChina
Created August 22, 2018 01:17
Show Gist options
  • Save AJLoveChina/8e355690783e0de20a0e73521b2d5216 to your computer and use it in GitHub Desktop.
Save AJLoveChina/8e355690783e0de20a0e73521b2d5216 to your computer and use it in GitHub Desktop.
custom promise. is likely as the window.Promise
let once = function (fn) {
let used = false;
return function () {
if (!used) {
fn.apply(null, arguments);
used = true;
}
}
};
let customPromise = function (fn) {
this.ex = null;
let valStack = [];
let exStack = [];
let thenHandlerStack = [];
let catchHandlerStack = [];
let resolve = function (data) {
valStack.push(data);
isExistValueThenDO();
};
let reject = function (ex) {
exStack.push(ex);
isExistExceptionThenDO();
};
let isExistValueThenDO = function () {
if (valStack.length > 0 && thenHandlerStack.length > 0) {
try {
let res = thenHandlerStack.pop().call(null, valStack.pop());
dealThenOrCatchResponse(res);
} catch (ex) {
reject(ex);
}
}
};
let isExistExceptionThenDO = function () {
if (exStack.length > 0 && catchHandlerStack.length > 0) {
try {
let res = catchHandlerStack.pop().call(null, exStack.pop());
dealThenOrCatchResponse(res);
} catch (ex) {
reject(ex);
}
}
};
let dealThenOrCatchResponse = function (res) {
if (res instanceof Error) {
exStack.push(res);
} else {
valStack.push(res);
}
};
this.then = function (fn) {
thenHandlerStack.push(fn);
isExistValueThenDO();
return this;
};
this.catch = function (fn) {
catchHandlerStack.push(fn);
isExistExceptionThenDO();
return this;
};
try {
fn.call(null, once(resolve), once(reject));
} catch (ex) {
reject(ex);
}
};
let promise = new customPromise((resolve, reject) => {
resolve(0);
setTimeout(() => resolve(1), 1000);
});
promise.then(function (val) {
console.log(val);
return "from then 1";
}).then(function (data) {
console.log(data);
}).then((data) => {
console.log(data);
return "me is not undefined"
}).then(data => {
console.log(data);
dfasdf()
}).catch(ex => {
console.log(ex);
return "exception"
}).then(function (data) {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment