Izopi4a
Izopi4a

Reputation: 500

Promise a callback function and a ajax call in the same function

I have this question:

I user google recapcha and I have a server side loaded JS data. The way I am using recapcha is

<script src="https://www.google.com/recaptcha/api.js?onload=onScriptLoaded&render=explicit"></script>

which means I wait for this function onScriptLoaded and then a manually render the capchas.

I also include this inside my head tag

<script type="text/javascript" src="/profile/js"></script>

which return something like

userData = {};
userData.id = 1;
userData.name = 'koko';

now this is ok, but what I am trying to do is some sort of "promisses ?", basiccaly i am looking for a syntax like

$.when( onScriptLoaded, $.getScript( "/profile/js" ) ).done(function( a1, a2 ) {
    console.log(arguments);
});

so I can enter all my callback functions, loading etc.. and then init my JS class ( because I use the values of those callbacks )

In this case however i get an error

Uncaught ReferenceError: onScriptLoaded is not defined

because i havnen't explain what "onScriptLoaded" is.

So.. is there a way to make this kind of syntax work in my case

Thanks!

Upvotes: 0

Views: 281

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

You could try something like

//a promise that will be resolved once the googe captcha code is executed
var captchaPromise;
(function () {
    var deferred = jQuery.Deferred();
    //the onload callback for google captcha
    window.onScriptLoaded = function (data) {
        console.log('looks like the captcha is complered now', arguments);
        //once the captcha callback is invoked resolve the deferred
        deferred.resolve(data);
    }
    captchaPromise = deferred.promise();
})();

//use the when method with the captch promise and ajax promise
$.when(captchaPromise, $.getScript("/profile/js")).done(function (a1, a2) {
    console.log('when callback');
    console.log(arguments);
});

Demo: Fiddle

Upvotes: 1

Related Questions