0

I have function like in some of sub pages,

function fuct(){

....
somecode inside
}

What I want to do is execute another function called function anotherfunction after successful execution of function funct which is in main html page. And I dont want to call anotherfunction in body of fuct.

Can I do something like,

on.succss of funct call anotherfunction

oyks
  • 11
  • 6
  • 1
    It sounds a lot like you want promises - check out https://www.promisejs.org/ – Evan Knowles Sep 19 '14 at 06:17
  • simply when you call first function, call another function after just that.. – Jaydeep Pedhadiya Sep 19 '14 at 06:18
  • What is in your first function? If it's all synchronous (e.g. no networking), then you can just call your second function right after you call your first: `a(); b();`. If your first function has asynchronous operations in it, then you will have to be more specific about what it has in it. Far too little information disclosed here to do anything more than make wild guesses. – jfriend00 Sep 19 '14 at 06:20
  • If your first function has a return value, you can check the return value after it finishes and decide what to do next based on that. Nothing more to say without you disclosing more about the real problem you're trying to solve with more real code. – jfriend00 Sep 19 '14 at 06:37

2 Answers2

3

The missing keyword is callback.

You can have something like this:

function funct(callback) {
   // do something
   callback(a, b, c, ..., n);
}

function anotherFunction(a, b, c, ..., n) {
   // do something
}

funct(anotherFunction);

JSFIDDLE


Another way is using promises:

function func() {
    var deferred = new $.Deferred();

    // do something
    deferred.resolve(position);


    // return promise so that outside code cannot reject/resolve the deferred
    return deferred.promise();
};

funct().then(anotherFunction);
Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
3

do something like

function function1()
{
    //if succeeds
    return true;
}

then where you need

if (function1()) {
    //call another function
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • Why do this? What if `function1()` doesn't return anything. This seems like another wild guess and not a general answer. – jfriend00 Sep 19 '14 at 06:21
  • Yeah, which means it isn't a general purpose answer. The fact is that the OP's question is not clear at all so all you can do is guess or explain all possible answers given the uncertainty in the question. – jfriend00 Sep 19 '14 at 06:23
  • yes, somewhat it is. we can just suggest him how can he do this. – Sougata Bose Sep 19 '14 at 06:24