Expanding Promises to Support Progress Reporting

So, I wanted to expand Promise to have “progress” so that I could report it using Promise for my Async tasks.

So I distributed Promise as follows:

class promisePro extends Promise {
    constructor(fn) {
        super(function (resolve, reject) {
            fn(resolve, reject, this._progress.bind(this));
        });
    }

    _progress(v) {
        if (this.progressCB)
            this.progressCB(v);
    }

    progress(fn) {
        this.progressCB = fn;
    }
}

and used it:

function ptest() {
    return new promisePro((resolve, reject, progress) => {
        setTimeout(() => {
            progress(0.3)
        }, 1000)
        setTimeout(() => {
            progress(0.6)
        }, 2000)
        setTimeout(() => {
            progress(0.9)
        }, 3000)
        setTimeout(() => {
            resolve(1)
        }, 4000)
    })
}

and used itt:

ptest().then((r) => {
    console.log('finiished: ' + r)
}).progress((p) => {
    console.log('progress: ' + p)
})

and got this error:

ptest().then((r) => {
    ^
TypeError: Promise resolve or reject function is not callable

What am I doing wrong here?

I used node 7.5 upgraded to 8.4. Got this error in both versions.

Thank.

+4
source share
1 answer

There are a few issues to look for here.

-, "this" undefined, super. - , sel

constructor(fn) {
    let self;
    super(function (resolve, reject) {
        fn(resolve, reject, value => self._progress(value));
    });
    self = this;
}

-, , , , "then", , , undefined . - "this" , ,

progress(fn) {
    this.progressCB = fn;
    return this;
}

ptest().progress((p) => {
    console.log('progress: ' + p)
}).then((r) => {
    console.log('finiished: ' + r)
})

promises ( , ).

, Observables? http://reactivex.io/rxjs/

+2

Source: https://habr.com/ru/post/1684968/


All Articles