gpt4 book ai didi

javascript - 运行 Q Promise 并连续获取进度

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:39 25 4
gpt4 key购买 nike

我有这段代码,我希望这两个 Promise 顺序运行,结果应该是这样的:

a progress: 20
a progress: 40
a progress: 60
a progress: 80
a progress: 100
a resolve: a

b progress: 20
b progress: 40
b progress: 60
b progress: 80
b progress: 100
b resolve: b

但我明白了:

a progress: 20
b progress: undefined
a progress: 40
b progress: undefined
a progress: 60
b progress: undefined
a progress: 80
b progress: undefined
a progress: 100
a resolve: a
b progress: undefined
b progress: 20
b progress: 40
b progress: 60
b progress: 80
b progress: 100
b resolve: b

这是我的整个代码:

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 b = function(){
return q.Promise(function(resolve, reject, notify){
var percentage = 0;
var interval = setInterval(function() {
percentage += 20;
notify(percentage);
if (percentage === 100) {
resolve("b");
clearInterval(interval);
}
}, 500);
});
};


a().then(function(res) {
console.log('a resolve: '+res);
return b();
},
errorHandler,
function(progress){
console.log('a progress: '+progress);
})

//call b()
.then(function(res){
console.log('b resolve: '+res);
},
errorHandler,
function(progress){
console.log('b progress: '+progress);
});

function errorHandler(err) {
console.log('Error Handler:', err);
}

最佳答案

您可以使用Q's chaining .

a()
.then(
function(res) {
b().then(function(resb) {
console.log('b resolve: '+resb);
},
errorHandler,
function(progress){
console.log('b progress: '+progress);
});
},
errorHandler,
function(progress){
console.log('a progress: '+progress);
});

使用 fin 也可以:

a()
.then(
function(res) {
console.log('a resolve: '+res);
},
errorHandler,
function(progress){
console.log('a progress: '+progress);
})
.fin(function() {
b().then(function(res) {
console.log('b resolve: '+res);
},
errorHandler,
function(progress){
console.log('b progress: '+progress);
});
});

让我们看看原始代码的流程:

a().then(function(res) {
console.log('a resolve: '+res);
return b(); // (0) here we only create promise for 'b'
},
errorHandler,
function(progress){
console.log('a progress: '+progress); // (1) here Q calls progress's callback
})

//call b()
.then(function(res){
console.log('b resolve: '+res); // (2) it's called in the end
},
errorHandler,
function(progress){
console.log('b progress: '+progress); // (1) and here Q calls progress's callback
});

'b Progress: undefined' 是因为完全没有进度,但是调用了回调。当 Promise 未完成时,会调用进度回调。当您返回某些内容或调用“解决”时, promise 就会得到满足。

关于javascript - 运行 Q Promise 并连续获取进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33233721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com