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):
$(\'.loadin
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:
function delay(ms){ // quick promisified delay function
return new Promise(function(r){ setTimeout(r,ms);});
}
var promises = $('.elements').map(function(i, el){
return delay(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) {
return delay(100).then(function(){
$(el).blockingFunction();
});
});
return Promise.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(){ return delay(100); }).
then(function(){
$('.newElements').each(function(i, el) { $(el).blockingFunction(); });
}).then(function(){
$('.loading-spinner').hide();
}).catch(function(err){
throw err;
});