1

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.

Rino Raj
  • 6,264
  • 2
  • 27
  • 42
leoOrion
  • 1,833
  • 2
  • 26
  • 52

2 Answers2

10

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.');
});
uksz
  • 18,239
  • 30
  • 94
  • 161
1

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*/ ) {

    });
Zorken17
  • 1,896
  • 1
  • 10
  • 16