ECMAScript Promise中的进度通知 [英] progress notifications in ECMAScript Promise
问题描述
我们正在使用 ECMAScript 6承诺
。
我们需要对最终用户实施进度通知(这是纯UX要求)。我知道其他承诺框架( 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承诺永远不会有进步。承诺代表一个单一的最终价值。如果你想要多个值,你可以查看可观察值 - 或者将其转化为承诺返回函数。
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.
这是从我们的指南 bluebird :
进程具有使用promise进阶处理程序的API的可组合性和链接问题。由于其他图书馆远离进度API,因为它与承诺无关,Bluebird也是如此。实现进度条的常见用例可以使用类似于 IProgress 。
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后:
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屋!