Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

javascript - progress notifications in ECMAScript Promise

We're using ECMAScript 6 promises.

We need to implement progress notifications to the end-user (this is pure UX requirement). I know that other promise frameworks (Q promise library, for ex.) allows that.

How can we adopt some kind of progress indication most elegantly?

Or should we migrate to a different framework? (I don't know how to estimate the effort of the latter)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ES2015 promises will never have progression. Promises represent a singular eventual value. If you want multiple values you can look into observables - or put the progress on the promise returning function.

Putting the progress on the promise returning function is pretty easy. Basically you take a callback as a parameter to the function and call it whenever a progress notification should happen.

Here is some text adapted from our guide at bluebird:

Progression has composability and chaining issues with APIs that use promise progression handlers. As other libraries move away from the progression API since it really has little to do with promises, so will Bluebird. Implementing the common use case of progress bars can be accomplished using a pattern similar to IProgress in C#.

Using jQuery before:

Promise.resolve($.get(...))
    .progressed(function() {
        // ...
    })
    .then(function() {
        // ...
    })
    .catch(function(e) {
        // ...
    })

Using jQuery after:

Promise.resolve($.get(...).progress(function() {
        // ...
    }))
    .then(function() {
        // ...
    })
    .catch(function(e) {
        // ...
    })

Implementing general progress interfaces like in C#:

function returnsPromiseWithProgress(progressHandler) {
    return doFirstAction().tap(function() {
        progressHandler(0.33);
    }).then(doSecondAction).tap(function() {
        progressHandler(0.66);
    }).then(doThirdAction).tap(function() {
        progressHandler(1.00);
    });
}

returnsPromiseWithProgress(function(progress) {
    ui.progressbar.setWidth((progress * 200) + "px"); // update with on client side
}).then(function(value) { // action complete
   // entire chain is complete.
}).catch(function(e) {
    // error
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...