Mike2012
Mike2012

Reputation: 7725

How to know when all promises have been rejected or resolved with basic js promises

I am trying to switch to loading all the resources in my web app asynchronously using basic JS promises.

Here is the ScriptLoader I am using to load all of my .js files:

function ScriptLoader() {
this.promises = [];

this.add = function(url, doneFunc) {
    var promise = new Promise(function(resolve, reject) {

        var script = document.createElement('script');
        script.src = url;

        script.addEventListener('load', function() {
            resolve(script);
            if(doneFunc)
                doneFunc(true);
        }, false);

        script.addEventListener('error', function() {
            reject(script);
            if(doneFunc)
                doneFunc();
            console.log(url + ' was rej');
        }, false);
        document.head.appendChild(script);
    });

    this.promises.push(promise);
};

}

and I call this function to load JS files:

function IncludeJS(jsFile, scriptDoneLoading) {
    app.scriptLoader.add('js/'+ jsFile, scriptDoneLoading);
}

I need to know when all of the js file have been resolved or rejected but it is unclear how I can know this.

Is there some callback that gets sent when all promises have been handled?

Upvotes: 1

Views: 346

Answers (2)

Chris Perkins
Chris Perkins

Reputation: 809

Promise.all will let you check multiple promises.

I would modify add so that it returns a promise. And then, instead of passing it a 'doneFunc' to execute when it is complete, just hang something onto the .then().

add = function(url) {
    var promise = new Promise(function(resolve, reject) {

        var script = document.createElement('script');
        script.src = url;

        script.addEventListener('load', function() {
            resolve(script);
        }, false);

        script.addEventListener('error', function() {
            reject(script);
            
        }, false);
        document.head.appendChild(script);
      
    });

    return promise
};

// here is how to call
add('myscript.js').then(function(scriptNode){
  console.log("completed");
  })
  .catch(function(er){
   console.log("failed", er);
  });

//and here is how to load multiple
var array_of_promises = ['myscript.js', 'otherscript.js'].map(add)
Promise.all(array_of_promises).then(function(){
  console.log("they are all loaded");
  })
  

Upvotes: 2

tcooc
tcooc

Reputation: 21209

Assuming you're using the new ES6 Promise class, you can use Promise.all()

Promise.all(app.scriptLoader.promises).then(onSuccess, onError);

onSuccess is called iff all promises resolve, and onError is called if any promise is rejected, first argument being the first rejection that happened.

Upvotes: 3

Related Questions