What is cleanest way to turn Array of JQuery Promises into a JQuery Promise of an Array?

前端 未结 2 1081
失恋的感觉
失恋的感觉 2020-12-05 15:38

I run into the situation where I have multiple JQuery Promises in an Array

var arrayOfPromises = [ $.Deferred(), $.Deferred(), $.Deferred(), $.Deferred() ]
<         


        
2条回答
  •  抹茶落季
    2020-12-05 16:03

    It also bothered me alot to always type the "ugly" line $.when.apply when we need to invoke it on multiple promises. But Function.prototype.bind for the rescue!

    var when = Function.prototype.apply.bind( jQuery.when, null );
    

    Now, we can just call

    when( someArrayWithPromises ).done(function() {
    });
    

    Function.prototype.bind is part of ES5 and is very widely available across browsers. There are a ton of easy shims available if you need to support very old'ish browsers aswell

提交回复
热议问题