通知Q承诺Node.js的进度

时间:2015-10-20 07:27:50

标签: javascript node.js promise q

我想使用Q Promise进度功能,我有这个代码,我希望抓住进度,当进度为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

为什么?

1 个答案:

答案 0 :(得分:0)

如果我尝试运行您的脚本(节点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语句的结果,该语句不返回任何内容。

相关问题