Search code examples
promisebluebird

Implement a "promise always" return function


So i have these 2 functions loadScriptWithBluebird and loadBluebird,
loadScriptWithBluebird is supposed to be generic for the main flow of the application, and will always return a promise.
I wonder if it is possible with some kind of a pattern to use loadBluebird inside loadScriptWithBluebird

function loadBluebird(callback){
    //load the script and callback ...
    script.onload = function() {
        callback();
    };
}

function loadScriptWithBluebird (src){

    if(isBluebirdAvailable()){
        return new Bluebird(function(resolve, reject){
            //load the script and resolve ...
            script.onload = function() {
                resolve();
            };
        });
    }else{
        //issue starts here since i obviously cannot return inside the callback
        loadBluebird(function(){
            loadScriptWithBluebird(src) 
        })
    }

},

So the flow of the application will look like this :

loadScriptWithBluebird('jquery').then(function(){
    //...
});

Thanks.


Solution

  • No, you can't do that, since bluebird wouldn't yet be available when you need to return the promise. So simply ignore that, and rely on the caller of your loadScript function to already have loaded Bluebird. There's not really a way around this.