Checked all Promise sample, none of them is in ES6 syntax, this is weird, which age are we now. Simplest verison
class MyPromise {
constructor(fn) {
this.doneCallback = null;
fn(this.resolve.bind(this)); // resolve will be called in another function context, must bind here
}
resolve(result) {
this.doneCallback(result);
}
then(done) {
this.doneCallback = done;
return this;
}
}
function test() {
return new MyPromise(function (successResolve) {
setTimeout(function () {
console.log(100);
successResolve(1);
}, 1000);
});
}
test().then((d) => {
console.log('done' + d);
});
Added Promise chain.
class MyPromise {
constructor(fn) {
this.doneList = [];
fn(this.resolve.bind(this)); // resolve will be called in another function context, must bind here
}
resolve(result) {
var self = this;
setTimeout(function () {
self.doneList.forEach(function (fulfill) {
fulfill(result);
});
}, 0);
}
then(done) {
this.doneList.push(done);
return this;
}
}
function test() {
return new MyPromise(function (successResolve) {
setTimeout(function () {
successResolve(1);
}, 1000);
});
}
test().then((d) => {
console.log('step1: ' + d);
}).then(_ => {
console.log('step2:');
}).then(m => {
console.log('step3: ' + m);
});