Zertix.net
Zertix.net

Reputation: 55

Jquery - Chain functions with deferred and promises but without setTimeout

I need to execute 2 functions one after the other with the stuff in function "A" fully completing before the stuff in function "B" executes...

I can't find an example that is not using setTimeout .. which is strange ...

I have the following example below ( from here ) , is it supposed to work ?? How could I test if it is working ? What dummy code could I use to simulate the part "//do stuff with SharePoint JSOM" taking 5 secs to 30 secs ,say .

var a = function() {
var defer = $.Deferred();

//do stuff with SharePoint JSOM

console.log('a() called');

return defer;
};

var b = function() {
var defer = $.Deferred();

console.log('b() called');


return defer;
};



a().then(b);

Upvotes: 3

Views: 1261

Answers (1)

eisbehr
eisbehr

Reputation: 12452

Simple use a promise (vanilla JS) and chain them with then.

function a() {
    return new Promise(function(resolve) {
        console.log("wait two seconds ...");

        // this timeout is only here for demo purpose ;)
        setTimeout(function() {
            console.log("A");
            resolve();
        }, 2000);
    });
}

function b() {
    console.log("B");
}

a().then(b);

If you want to use jQuery deffered its nearly the same.

function a() {
    var defer = $.Deferred();
    
    console.log("wait two seconds ...");

    // this timeout is only here for demo purpose ;)
    setTimeout(function() {
        console.log("A");
        defer.resolve();
    }, 2000);
    
    return defer;
}

function b() {
    console.log("B");
}

a().then(b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 4

Related Questions