ECMAScript Promise 中的进度通知 [英] progress notifications in ECMAScript Promise

查看:23
本文介绍了ECMAScript Promise 中的进度通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 ECMAScript 6 承诺.

我们需要向最终用户实施进度通知(这是纯粹的 UX 要求).我知道其他 Promise 框架(例如 Q promise 库)允许这样做.

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)

推荐答案

ES2015 承诺永远不会有进展.Promises 代表一个单一的最终值.如果您想要多个值,您可以查看 observables - 或者将进度放在 Promise 返回函数上.

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.

将进度放在 Promise 返回函数上非常容易.基本上,您将回调作为函数的参数,并在发生进度通知时调用它.

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.

以下是改编自我们在 bluebird 上的指南的一些文字:

Here is some text adapted from our guide at bluebird:

Progression 与使用 promise 进程处理程序的 API 存在可组合性和链接问题.随着其他库远离progression API,因为它实际上与promise 关系不大,Bluebird 也将如此.可以使用类似于 IProgress 在 C# 中.

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#.

之前使用 jQuery:

Using jQuery before:

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

之后使用 jQuery:

Using jQuery after:

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

在 C# 中实现通用的进度接口:

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

这篇关于ECMAScript Promise 中的进度通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆