2015-10-20 24 views
0

通知Q承诺的进展我想用QPromise进步的功能,我有这样的代码,我想赶上进度,当进度为100,则解决Promise在Node.js的

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 

为什么?

回答

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 -function或者您可以使用特殊.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(进度)打印undefined,因为该功能是听以前.then语句来,它不返回任何结果。

+0

如果我使用多个承诺一个错误处理程序,这应该工作?现在你说如果一个特定的承诺抛出错误,错误处理函数触发 – Fcoder

+0

我更新了我的答案,以进一步澄清这一点。 – PatrickD

+0

似乎已取消进展:https://github.com/kriskowal/q/wiki/API-Reference#promiseprogressonprogress – Fcoder