Ass*_*esh 29 javascript promise ecmascript-6
我们正在使用ECMAScript 6 promises.
我们需要向最终用户实施进度通知(这是纯UX要求).我知道其他的promise框架(例如,Q promise库)允许这样做.
我们怎样才能最优雅地采用某种进步指示?
或者我们应该迁移到不同的框架?(我不知道如何评估后者的努力)
Ben*_*aum 26
ES2015承诺永远不会有进展.承诺代表了一种独特的最终价值.如果你想要多个值,你可以查看observables - 或者将进度放在promise返回函数上.
将进度放在promise返回函数上非常简单.基本上,您将回调作为函数的参数,并在发生进度通知时调用它.
以下是一些改编自蓝鸟指南的文字:
升级具有使用promise渐进处理程序的API的可组合性和链接问题.由于其他图书馆远离进展API,因为它与承诺无关,Bluebird也是如此.实现进度条的常见用例可以使用类似于C#中的IProgress的模式来完成.
之前使用jQuery:
Promise.resolve($.get(...))
.progressed(function() {
// ...
})
.then(function() {
// ...
})
.catch(function(e) {
// ...
})
Run Code Online (Sandbox Code Playgroud)
之后使用jQuery:
Promise.resolve($.get(...).progress(function() {
// ...
}))
.then(function() {
// ...
})
.catch(function(e) {
// ...
})
Run Code Online (Sandbox Code Playgroud)
实现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
});
Run Code Online (Sandbox Code Playgroud)