[英]notify Q Promise progress in Node.js
我想使用Q
Promise
Progress功能,我有這段代碼,我想捕獲進度,當進度為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
為什么?
如果我嘗試運行您的腳本(節點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
您必須將進度回調作為.progress()
第三個參數注冊.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(進度)打印undefined
,因為功能是聽以前的結果.then
語句來,它沒有返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.