Promise.all resolving earlier than expected

前端 未结 1 952
我在风中等你
我在风中等你 2021-01-15 20:34

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         


        
相关标签:
1条回答
  • 2021-01-15 21:06

    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;
    });
    
    0 讨论(0)
提交回复
热议问题