Promise.all Resolving Earlier Than Expected
I'm writing my first piece of code using Promises and am getting some unexpected results. I had some code that looked like this (using jQuery): $('.loading-spinner').show(); $('.e
Solution 1:
You're calling Promise.all
on promises2
before you populate it, in fact when you call it it contains an empty array so it calls Promise.all
on an empty array and thus it resolves immediately without waiting for the promises in promises
.
Quick fix:
functiondelay(ms){ // quick promisified delay functionreturnnewPromise(function(r){ setTimeout(r,ms);});
}
var promises = $('.elements').map(function(i, el){
returndelay(100).then(function(){
$(el).replaceWith(function() {
// Code to generate and return a replacement element
});
});
Promises.all(promises).then(function(els){
var ps = $('.newElements').map(function(i, el) {
returndelay(100).then(function(){
$(el).blockingFunction();
});
});
returnPromise.all(ps);
}).then(function(){
$('.loading-spinner').hide();
});
We can do better though, there is no reason to fire n
timeouts for n
elements:
delay(100).then(function(){
$(".elements").each(function(i,el){
$(el).replaceWith(function(){ /* code to generate element */});
});
}).
then(function(){ returndelay(100); }).
then(function(){
$('.newElements').each(function(i, el) { $(el).blockingFunction(); });
}).then(function(){
$('.loading-spinner').hide();
}).catch(function(err){
throw err;
});
Post a Comment for "Promise.all Resolving Earlier Than Expected"