leoOrion
leoOrion

Reputation: 1957

How to Know when a function Completes

Is there any way to find out when a function completes. I need to run another function but only after one function completes. Something like this...

$(document).ready(function(){});

Except with a function rather than the document.

Upvotes: 1

Views: 93

Answers (2)

Zorken17
Zorken17

Reputation: 1896

You can also use jQuery deferred like this:

var myPromise = function() {
    var dfd = $.deferred();

    if (/* this i ok*/) {
        dfd.resolve( /* somthing to send with the result */ );
    } else {
        dfd.reject( /* somthing to send with the result */);
    }

    return dfd.promise();
}

myPromise().then(function succsses( /* the message*/ ) {

    },
    function fail(/* the message*/ ) {

    });

Upvotes: 1

uksz
uksz

Reputation: 18699

You can either create a promise, or use a callback.

Here is a example of a promise (it has a success (resolve), and reject(something went wrong)):

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything is OK */) {
    resolve("Stuff worked!");
  }
  else { // something went wrong
    reject(Error("It broke"));
  }
});

And you use it like this:

promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

And here is a example of callback:

function giveMeAlert(callback) {
    alert('I am main function');
    callback();
}

giveMeAlert(function() {
    alert('I am a callback function.');
});

Upvotes: 10

Related Questions