自制ES6 Promise

来源:互联网 发布:深圳软件学校 编辑:程序博客网 时间:2024/05/01 15:21

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);});


原创粉丝点击