Skip to content

Instantly share code, notes, and snippets.

@TechQuery
Created July 30, 2018 09:45
Show Gist options
  • Save TechQuery/b714014685f07d4c0328559fb73308a3 to your computer and use it in GitHub Desktop.
Save TechQuery/b714014685f07d4c0328559fb73308a3 to your computer and use it in GitHub Desktop.
Promise in ES 6
(() => {
class Promise {
constructor(main) {
this.result = null;
this.state = -1;
this.callback = [ ];
const end = (type, result) => {
if (this.state > -1) return;
this.state = type, this.result = result;
setTimeout(() => {
for (let func of this.callback) func[type]( result );
this.callback.length = 0;
});
};
main(end.bind(null, 0), end.bind(null, 1));
}
then(resolve, reject) {
return new Promise((_resolve_, _reject_) => {
const callback = [
value => _resolve_(resolve( value )),
error => _reject_(reject( error ))
];
if (this.state < 0)
this.callback.push( callback );
else
callback[this.state]( this.result );
});
}
}
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(1));
setTimeout(() => reject(0));
});
function print(...text) {
console.log(...text);
document.body.append(text.join(' '), document.createElement('br'));
}
promise.then(
value => print(value) || 2,
error => print(error)
).then(
value => print(value)
);
setTimeout(
() => promise.then(value => print(value)).then(() => print(2))
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment