【问题标题】:notify Q Promise progress in Node.js在 Node.js 中通知 Q Promise 进度
【发布时间】:2015-10-20 16:09:15
【问题描述】:

我想使用QPromise进度功能,我有这个代码,我想捕捉进度,当进度为100时,然后解决Promise

var q = require("q");

var a =  function(){
    return q.Promise(function(resolve, reject, notify){
        var percentage = 0;
        var interval = setInterval(function() {
            percentage += 20;
            notify(percentage);
            if (percentage === 100) {
                resolve("a");
                clearInterval(interval);
            }
        }, 500);
    });
};

var master = a();

master.then(function(res) {
    console.log(res);
})

.then(function(progress){
    console.log(progress);
});

但我得到这个错误:

Error: Estimate values should be a number of miliseconds in the future

为什么?

【问题讨论】:

    标签: javascript node.js promise q


    【解决方案1】:

    如果我尝试运行您的脚本(节点 4.2.1),我没有收到此错误,但您从未听过承诺的进度。 你需要将progressHandler注册为.then函数的第三个参数:

    var q = require("q");
    
    var a =  function(){
        return q.Promise(function(resolve, reject, notify){
            var percentage = 0;
            var interval = setInterval(function() {
                percentage += 20;                
                notify(percentage);
                if (percentage === 100) {
                    resolve("a");
                    clearInterval(interval);
               }
            }, 500);
        });
    };
    
    function errorHandler(err) {
      console.log('Error Handler:', err);
    }
    
    var master = a();
    
    master.then(function(res) {
        console.log(res);
    }, 
    errorHandler,
    function(progress){
        console.log(progress);
    });
    

    输出:

    20
    40
    60
    80
    100
    a
    

    您必须将进度回调注册为.then 函数的第三个参数,或者您可以使用特殊的.progress() 简写,参见https://github.com/kriskowal/q#progress-notification

    这是带有progress 简写的调用链:

    var master = a();
    master.progress(function(progress{
        console.log(progress)})
    .then(function(res) {
        console.log(res);
    });
    

    在您的代码中,console.log(progress) 打印undefined,因为该函数是侦听前一个.then-statement 的结果,它什么也不返回。

    【讨论】:

    • 如果我对多个承诺使用一个错误处理程序,这应该有效吗?现在你说如果一个特定的承诺抛出错误,一个错误处理函数就会触发
    • 我更新了我的答案以进一步澄清这一点。
    • 似乎进度已被弃用:github.com/kriskowal/q/wiki/…
    • @Fcoder — 只有.observeEstimate 是。 .progress() 仍然是一部分,甚至是 the introduction 的一部分。
    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2013-08-02
    • 2013-02-05
    • 1970-01-01
    相关资源
    最近更新 更多