In JavaScript, how to execute next function from an array of functions

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
19
down vote

favorite
2












I have an array of functions, as in:



funcArray = [func1, func2, func3];


When in a given function, I want to execute the next function in the array. How do I do this? Here is my basic skeleton:



function func1() 
// I get current function caller
var currentFunc = func1.caller;

// I want to execute the next function. Happens to be func2 in the example.




I cannot use indexOf function, as one would for an array of strings or numbers.
NOTE: This question appears to be similar to this and the one it refers to. However, it is a different question.



I want to alter the sequence of processing by merely modifying the array. That's the goal. A possibly more efficient approach would be appreciated.



Clarification: Based upon some of the comments:
funcArray is global.



The goal is to implement middleware for a Node.js HTTP module in as simple and efficient a manner as possible without using any third-party modules.










share|improve this question



















  • 3




    I guess, you can't do this. func1 knows nothing about funcArray after you call it. Function is just a reference and it may be stored in an array, in object or wherever else. Caller function should worry about the order of execution in this case.
    – Yeldar Kurmangaliyev
    Aug 13 at 12:36







  • 18




    this is a classic exemple of the X Y problem : xyproblem.info what is your goal at first place and what general problem are you trying to solve?
    – mpm
    Aug 13 at 12:38






  • 2




    What makes you think that you couldn't use funcArray.indexOf(func1)? It works with strings, numbers or objects like functions.
    – Bergi
    Aug 13 at 13:55






  • 2




    @Sam Functions are objects and compared by identity. Having multiple different functions with the same name won't make them equal.
    – Bergi
    Aug 13 at 14:09






  • 2




    @Sam Object equality is pretty cheap, it's more or less just a pointer comparison. But still, to suggest an efficient solution we need to know more about your actual problem. Why would the func1 need to know about func2 at all? Shouldn't they be executed separately, by the caller? Do you just want to try calling the array functions in a loop until the first returns true or something?
    – Bergi
    Aug 13 at 14:16














up vote
19
down vote

favorite
2












I have an array of functions, as in:



funcArray = [func1, func2, func3];


When in a given function, I want to execute the next function in the array. How do I do this? Here is my basic skeleton:



function func1() 
// I get current function caller
var currentFunc = func1.caller;

// I want to execute the next function. Happens to be func2 in the example.




I cannot use indexOf function, as one would for an array of strings or numbers.
NOTE: This question appears to be similar to this and the one it refers to. However, it is a different question.



I want to alter the sequence of processing by merely modifying the array. That's the goal. A possibly more efficient approach would be appreciated.



Clarification: Based upon some of the comments:
funcArray is global.



The goal is to implement middleware for a Node.js HTTP module in as simple and efficient a manner as possible without using any third-party modules.










share|improve this question



















  • 3




    I guess, you can't do this. func1 knows nothing about funcArray after you call it. Function is just a reference and it may be stored in an array, in object or wherever else. Caller function should worry about the order of execution in this case.
    – Yeldar Kurmangaliyev
    Aug 13 at 12:36







  • 18




    this is a classic exemple of the X Y problem : xyproblem.info what is your goal at first place and what general problem are you trying to solve?
    – mpm
    Aug 13 at 12:38






  • 2




    What makes you think that you couldn't use funcArray.indexOf(func1)? It works with strings, numbers or objects like functions.
    – Bergi
    Aug 13 at 13:55






  • 2




    @Sam Functions are objects and compared by identity. Having multiple different functions with the same name won't make them equal.
    – Bergi
    Aug 13 at 14:09






  • 2




    @Sam Object equality is pretty cheap, it's more or less just a pointer comparison. But still, to suggest an efficient solution we need to know more about your actual problem. Why would the func1 need to know about func2 at all? Shouldn't they be executed separately, by the caller? Do you just want to try calling the array functions in a loop until the first returns true or something?
    – Bergi
    Aug 13 at 14:16












up vote
19
down vote

favorite
2









up vote
19
down vote

favorite
2






2





I have an array of functions, as in:



funcArray = [func1, func2, func3];


When in a given function, I want to execute the next function in the array. How do I do this? Here is my basic skeleton:



function func1() 
// I get current function caller
var currentFunc = func1.caller;

// I want to execute the next function. Happens to be func2 in the example.




I cannot use indexOf function, as one would for an array of strings or numbers.
NOTE: This question appears to be similar to this and the one it refers to. However, it is a different question.



I want to alter the sequence of processing by merely modifying the array. That's the goal. A possibly more efficient approach would be appreciated.



Clarification: Based upon some of the comments:
funcArray is global.



The goal is to implement middleware for a Node.js HTTP module in as simple and efficient a manner as possible without using any third-party modules.










share|improve this question















I have an array of functions, as in:



funcArray = [func1, func2, func3];


When in a given function, I want to execute the next function in the array. How do I do this? Here is my basic skeleton:



function func1() 
// I get current function caller
var currentFunc = func1.caller;

// I want to execute the next function. Happens to be func2 in the example.




I cannot use indexOf function, as one would for an array of strings or numbers.
NOTE: This question appears to be similar to this and the one it refers to. However, it is a different question.



I want to alter the sequence of processing by merely modifying the array. That's the goal. A possibly more efficient approach would be appreciated.



Clarification: Based upon some of the comments:
funcArray is global.



The goal is to implement middleware for a Node.js HTTP module in as simple and efficient a manner as possible without using any third-party modules.







javascript node.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 13 at 19:56









Peter Mortensen

12.9k1983111




12.9k1983111










asked Aug 13 at 12:34









Sam

1,94132251




1,94132251







  • 3




    I guess, you can't do this. func1 knows nothing about funcArray after you call it. Function is just a reference and it may be stored in an array, in object or wherever else. Caller function should worry about the order of execution in this case.
    – Yeldar Kurmangaliyev
    Aug 13 at 12:36







  • 18




    this is a classic exemple of the X Y problem : xyproblem.info what is your goal at first place and what general problem are you trying to solve?
    – mpm
    Aug 13 at 12:38






  • 2




    What makes you think that you couldn't use funcArray.indexOf(func1)? It works with strings, numbers or objects like functions.
    – Bergi
    Aug 13 at 13:55






  • 2




    @Sam Functions are objects and compared by identity. Having multiple different functions with the same name won't make them equal.
    – Bergi
    Aug 13 at 14:09






  • 2




    @Sam Object equality is pretty cheap, it's more or less just a pointer comparison. But still, to suggest an efficient solution we need to know more about your actual problem. Why would the func1 need to know about func2 at all? Shouldn't they be executed separately, by the caller? Do you just want to try calling the array functions in a loop until the first returns true or something?
    – Bergi
    Aug 13 at 14:16












  • 3




    I guess, you can't do this. func1 knows nothing about funcArray after you call it. Function is just a reference and it may be stored in an array, in object or wherever else. Caller function should worry about the order of execution in this case.
    – Yeldar Kurmangaliyev
    Aug 13 at 12:36







  • 18




    this is a classic exemple of the X Y problem : xyproblem.info what is your goal at first place and what general problem are you trying to solve?
    – mpm
    Aug 13 at 12:38






  • 2




    What makes you think that you couldn't use funcArray.indexOf(func1)? It works with strings, numbers or objects like functions.
    – Bergi
    Aug 13 at 13:55






  • 2




    @Sam Functions are objects and compared by identity. Having multiple different functions with the same name won't make them equal.
    – Bergi
    Aug 13 at 14:09






  • 2




    @Sam Object equality is pretty cheap, it's more or less just a pointer comparison. But still, to suggest an efficient solution we need to know more about your actual problem. Why would the func1 need to know about func2 at all? Shouldn't they be executed separately, by the caller? Do you just want to try calling the array functions in a loop until the first returns true or something?
    – Bergi
    Aug 13 at 14:16







3




3




I guess, you can't do this. func1 knows nothing about funcArray after you call it. Function is just a reference and it may be stored in an array, in object or wherever else. Caller function should worry about the order of execution in this case.
– Yeldar Kurmangaliyev
Aug 13 at 12:36





I guess, you can't do this. func1 knows nothing about funcArray after you call it. Function is just a reference and it may be stored in an array, in object or wherever else. Caller function should worry about the order of execution in this case.
– Yeldar Kurmangaliyev
Aug 13 at 12:36





18




18




this is a classic exemple of the X Y problem : xyproblem.info what is your goal at first place and what general problem are you trying to solve?
– mpm
Aug 13 at 12:38




this is a classic exemple of the X Y problem : xyproblem.info what is your goal at first place and what general problem are you trying to solve?
– mpm
Aug 13 at 12:38




2




2




What makes you think that you couldn't use funcArray.indexOf(func1)? It works with strings, numbers or objects like functions.
– Bergi
Aug 13 at 13:55




What makes you think that you couldn't use funcArray.indexOf(func1)? It works with strings, numbers or objects like functions.
– Bergi
Aug 13 at 13:55




2




2




@Sam Functions are objects and compared by identity. Having multiple different functions with the same name won't make them equal.
– Bergi
Aug 13 at 14:09




@Sam Functions are objects and compared by identity. Having multiple different functions with the same name won't make them equal.
– Bergi
Aug 13 at 14:09




2




2




@Sam Object equality is pretty cheap, it's more or less just a pointer comparison. But still, to suggest an efficient solution we need to know more about your actual problem. Why would the func1 need to know about func2 at all? Shouldn't they be executed separately, by the caller? Do you just want to try calling the array functions in a loop until the first returns true or something?
– Bergi
Aug 13 at 14:16




@Sam Object equality is pretty cheap, it's more or less just a pointer comparison. But still, to suggest an efficient solution we need to know more about your actual problem. Why would the func1 need to know about func2 at all? Shouldn't they be executed separately, by the caller? Do you just want to try calling the array functions in a loop until the first returns true or something?
– Bergi
Aug 13 at 14:16












5 Answers
5






active

oldest

votes

















up vote
30
down vote



accepted










Unless func1 closes over funcArray, you cannot have it reach out and find func2 and execute it, nor should you. Even if func1 does close over funcArray, it would be poor separation of concerns for func1 to reach out and find itself in funcArray and then execute func2.



Instead, have other code that's in charge of running the functions.



If they're synchronous



If the functions complete their work synchronously, then it's simply:



funcArray.forEach(fn => fn());


or



for (const fn of funcArray) 
fn();



or if the result of one function should be passed to the next, you can use reduce:



const finalResult = funcArray.reduce((previousResult, fn) => fn(previousResult), undefined);


...where undefined is the value to pass to func1.



If they're asynchronous



If they don't do their work synchronously, you'll need to provide them a way to notify their caller that they've completed their work. Promises are a good, standard way to do that, but you could use simple callbacks instead.



If you make them return promises, for instance, you can use the old promise reduce trick:



funcArray.reduce((p, fn) => 
return p.then(() =>
fn();
);
, Promise.resolve());


or if the result of one function should be passed to the next:



funcArray.reduce((p, fn) => 
return p.then(fn);
, Promise.resolve());


You can provide an argument to Promise.resolve to set the value to pass to func1 (without one, it'll receive undefined).






share|improve this answer


















  • 2




    i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
    – Nic Hartley
    Aug 13 at 17:19










  • @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
    – T.J. Crowder
    Aug 14 at 7:15

















up vote
4
down vote













You can bind to the function the index where it is in the array so you can use this index to get and call the next function:






var funcArray = [func1, func2];
var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

boundFuncArray[0]();

function func1(nextFunctionIndex)
console.log('func1 called');
// Execute next function:
var nextFunc = boundFuncArray[nextFunctionIndex + 1];
nextFunc && nextFunc();


function func2(nextFunctionIndex)
console.log('func2 called');
// Execute next function:
var nextFunc = boundFuncArray[nextFunctionIndex + 1];
nextFunc && nextFunc();





As T.J Crowder stated in the comment below, you can also bind the next function to the current one:






var funcArray = [func1, func2];
var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

boundFuncArray[0]();

function func1(nextFunc)
console.log('func1 called');
// Execute next function:
nextFunc && nextFunc();


function func2(nextFunc )
console.log('func2 called');
// Execute next function:
nextFunc && nextFunc();








share|improve this answer


















  • 1




    Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
    – T.J. Crowder
    Aug 13 at 13:02






  • 1




    bound, not binded
    – birdspider
    Aug 13 at 16:16

















up vote
3
down vote













You can get the current function's name with arguments.callee.name, loop through the array of functions, and call the next function:






funcArray = [func1, func2, func3];

// Only func1() and func2() will be documented since the others have repeating code

function func1()
// show the current function name
console.log(arguments.callee.name);

// loop the array of functions
for(var i = 0; i < funcArray.length; ++i)

// when the current array item is our current function name and
// another function exists after this then call it and break
if(funcArray[i] === arguments.callee && funcArray[i+1])

funcArray[i+1]();
break;




function func2()
console.log(arguments.callee.name);

// some logic which switches our next function to be func4()
funcArray[2] = func4;

for(var i = 0; i < funcArray.length; ++i)

if(funcArray[i] === arguments.callee && funcArray[i+1])

funcArray[i+1]();
break;




function func3()
console.log(arguments.callee.name);
for(var i = 0; i < funcArray.length; ++i)

if(funcArray[i] === arguments.callee && funcArray[i+1])

funcArray[i+1]();
break;




function func4()
console.log(arguments.callee.name);
for(var i = 0; i < funcArray.length; ++i)

if(funcArray[i] === arguments.callee && funcArray[i+1])

funcArray[i+1]();
break;




// call the first function
funcArray[0]();





Output:



func1
func2
func4





share|improve this answer






















  • Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
    – Kroltan
    Aug 13 at 13:32










  • @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
    – MonkeyZeus
    Aug 13 at 13:37






  • 1




    @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
    – Sam
    Aug 14 at 7:50











  • I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
    – MonkeyZeus
    Aug 14 at 12:05

















up vote
0
down vote













I dont know if your functions require certain parameters but this is the first thing that came to my mind.






var functArray = [
function()
console.log("function1 executed");
,
function()
console.log("function2 executed");
,
function()
console.log("function3 executed");
,
function()
console.log("function4 executed");
];

functArray.forEach(function(x)
x();
);








share|improve this answer



























    up vote
    0
    down vote













    The accepted answer and other comments did help me, but the way I implemented it is as follows:



    //The functions are defined as variables. 
    //They do not get hoisted, so must be defined first.
    func1 = function (arg1, arg2)
    //Code to do whatever...
    ...
    //Execute the next function.
    //The name of the function is returned by executing nextFunc()
    global[nextFunc()](arg1, arg2, arg3);


    func2 = function (arg1) //Note different type of args
    ...


    //Note that this is an array of strings representing function names.
    funcArray = ["func1", "func2", "func3",...]

    //Start the execution...
    func1(arg1, arg2);

    function nextFunc()
    var currentFuncName = nextFunc.caller.name;
    var index = funcArray.indexOf(currentFuncName);
    if (index < funcArray.length)
    return funcArray[index+1];



    The sequence of functions to be executed is easily managed through the array funcArray. The number or type of arguments is not fixed for each function. Additionally, the functions control if they should stop the chain or continue with the next function.



    It is very simple to understand requiring basic Javascript skills. No overheads of using Promises.



    "global" gets replaced by "window" for browser. This is a Node.js implementation. The use of function names in the array will, however, break if you minify the JS code. As I am going to use it on the server, I do not expect to minify it.






    share|improve this answer






















      Your Answer





      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51822513%2fin-javascript-how-to-execute-next-function-from-an-array-of-functions%23new-answer', 'question_page');

      );

      Post as a guest






























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      30
      down vote



      accepted










      Unless func1 closes over funcArray, you cannot have it reach out and find func2 and execute it, nor should you. Even if func1 does close over funcArray, it would be poor separation of concerns for func1 to reach out and find itself in funcArray and then execute func2.



      Instead, have other code that's in charge of running the functions.



      If they're synchronous



      If the functions complete their work synchronously, then it's simply:



      funcArray.forEach(fn => fn());


      or



      for (const fn of funcArray) 
      fn();



      or if the result of one function should be passed to the next, you can use reduce:



      const finalResult = funcArray.reduce((previousResult, fn) => fn(previousResult), undefined);


      ...where undefined is the value to pass to func1.



      If they're asynchronous



      If they don't do their work synchronously, you'll need to provide them a way to notify their caller that they've completed their work. Promises are a good, standard way to do that, but you could use simple callbacks instead.



      If you make them return promises, for instance, you can use the old promise reduce trick:



      funcArray.reduce((p, fn) => 
      return p.then(() =>
      fn();
      );
      , Promise.resolve());


      or if the result of one function should be passed to the next:



      funcArray.reduce((p, fn) => 
      return p.then(fn);
      , Promise.resolve());


      You can provide an argument to Promise.resolve to set the value to pass to func1 (without one, it'll receive undefined).






      share|improve this answer


















      • 2




        i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
        – Nic Hartley
        Aug 13 at 17:19










      • @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
        – T.J. Crowder
        Aug 14 at 7:15














      up vote
      30
      down vote



      accepted










      Unless func1 closes over funcArray, you cannot have it reach out and find func2 and execute it, nor should you. Even if func1 does close over funcArray, it would be poor separation of concerns for func1 to reach out and find itself in funcArray and then execute func2.



      Instead, have other code that's in charge of running the functions.



      If they're synchronous



      If the functions complete their work synchronously, then it's simply:



      funcArray.forEach(fn => fn());


      or



      for (const fn of funcArray) 
      fn();



      or if the result of one function should be passed to the next, you can use reduce:



      const finalResult = funcArray.reduce((previousResult, fn) => fn(previousResult), undefined);


      ...where undefined is the value to pass to func1.



      If they're asynchronous



      If they don't do their work synchronously, you'll need to provide them a way to notify their caller that they've completed their work. Promises are a good, standard way to do that, but you could use simple callbacks instead.



      If you make them return promises, for instance, you can use the old promise reduce trick:



      funcArray.reduce((p, fn) => 
      return p.then(() =>
      fn();
      );
      , Promise.resolve());


      or if the result of one function should be passed to the next:



      funcArray.reduce((p, fn) => 
      return p.then(fn);
      , Promise.resolve());


      You can provide an argument to Promise.resolve to set the value to pass to func1 (without one, it'll receive undefined).






      share|improve this answer


















      • 2




        i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
        – Nic Hartley
        Aug 13 at 17:19










      • @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
        – T.J. Crowder
        Aug 14 at 7:15












      up vote
      30
      down vote



      accepted







      up vote
      30
      down vote



      accepted






      Unless func1 closes over funcArray, you cannot have it reach out and find func2 and execute it, nor should you. Even if func1 does close over funcArray, it would be poor separation of concerns for func1 to reach out and find itself in funcArray and then execute func2.



      Instead, have other code that's in charge of running the functions.



      If they're synchronous



      If the functions complete their work synchronously, then it's simply:



      funcArray.forEach(fn => fn());


      or



      for (const fn of funcArray) 
      fn();



      or if the result of one function should be passed to the next, you can use reduce:



      const finalResult = funcArray.reduce((previousResult, fn) => fn(previousResult), undefined);


      ...where undefined is the value to pass to func1.



      If they're asynchronous



      If they don't do their work synchronously, you'll need to provide them a way to notify their caller that they've completed their work. Promises are a good, standard way to do that, but you could use simple callbacks instead.



      If you make them return promises, for instance, you can use the old promise reduce trick:



      funcArray.reduce((p, fn) => 
      return p.then(() =>
      fn();
      );
      , Promise.resolve());


      or if the result of one function should be passed to the next:



      funcArray.reduce((p, fn) => 
      return p.then(fn);
      , Promise.resolve());


      You can provide an argument to Promise.resolve to set the value to pass to func1 (without one, it'll receive undefined).






      share|improve this answer














      Unless func1 closes over funcArray, you cannot have it reach out and find func2 and execute it, nor should you. Even if func1 does close over funcArray, it would be poor separation of concerns for func1 to reach out and find itself in funcArray and then execute func2.



      Instead, have other code that's in charge of running the functions.



      If they're synchronous



      If the functions complete their work synchronously, then it's simply:



      funcArray.forEach(fn => fn());


      or



      for (const fn of funcArray) 
      fn();



      or if the result of one function should be passed to the next, you can use reduce:



      const finalResult = funcArray.reduce((previousResult, fn) => fn(previousResult), undefined);


      ...where undefined is the value to pass to func1.



      If they're asynchronous



      If they don't do their work synchronously, you'll need to provide them a way to notify their caller that they've completed their work. Promises are a good, standard way to do that, but you could use simple callbacks instead.



      If you make them return promises, for instance, you can use the old promise reduce trick:



      funcArray.reduce((p, fn) => 
      return p.then(() =>
      fn();
      );
      , Promise.resolve());


      or if the result of one function should be passed to the next:



      funcArray.reduce((p, fn) => 
      return p.then(fn);
      , Promise.resolve());


      You can provide an argument to Promise.resolve to set the value to pass to func1 (without one, it'll receive undefined).







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 14 at 7:14

























      answered Aug 13 at 12:37









      T.J. Crowder

      652k11211531251




      652k11211531251







      • 2




        i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
        – Nic Hartley
        Aug 13 at 17:19










      • @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
        – T.J. Crowder
        Aug 14 at 7:15












      • 2




        i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
        – Nic Hartley
        Aug 13 at 17:19










      • @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
        – T.J. Crowder
        Aug 14 at 7:15







      2




      2




      i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
      – Nic Hartley
      Aug 13 at 17:19




      i think it's worth mentioning Promise.all. It's not the answer to this question, but for those just looking to run all the functions in any order and do something when they're done, it's good.
      – Nic Hartley
      Aug 13 at 17:19












      @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
      – T.J. Crowder
      Aug 14 at 7:15




      @KRyan - Thanks! Fixed. Copy-and-paste error. :-)
      – T.J. Crowder
      Aug 14 at 7:15












      up vote
      4
      down vote













      You can bind to the function the index where it is in the array so you can use this index to get and call the next function:






      var funcArray = [func1, func2];
      var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

      boundFuncArray[0]();

      function func1(nextFunctionIndex)
      console.log('func1 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();


      function func2(nextFunctionIndex)
      console.log('func2 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();





      As T.J Crowder stated in the comment below, you can also bind the next function to the current one:






      var funcArray = [func1, func2];
      var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

      boundFuncArray[0]();

      function func1(nextFunc)
      console.log('func1 called');
      // Execute next function:
      nextFunc && nextFunc();


      function func2(nextFunc )
      console.log('func2 called');
      // Execute next function:
      nextFunc && nextFunc();








      share|improve this answer


















      • 1




        Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
        – T.J. Crowder
        Aug 13 at 13:02






      • 1




        bound, not binded
        – birdspider
        Aug 13 at 16:16














      up vote
      4
      down vote













      You can bind to the function the index where it is in the array so you can use this index to get and call the next function:






      var funcArray = [func1, func2];
      var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

      boundFuncArray[0]();

      function func1(nextFunctionIndex)
      console.log('func1 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();


      function func2(nextFunctionIndex)
      console.log('func2 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();





      As T.J Crowder stated in the comment below, you can also bind the next function to the current one:






      var funcArray = [func1, func2];
      var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

      boundFuncArray[0]();

      function func1(nextFunc)
      console.log('func1 called');
      // Execute next function:
      nextFunc && nextFunc();


      function func2(nextFunc )
      console.log('func2 called');
      // Execute next function:
      nextFunc && nextFunc();








      share|improve this answer


















      • 1




        Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
        – T.J. Crowder
        Aug 13 at 13:02






      • 1




        bound, not binded
        – birdspider
        Aug 13 at 16:16












      up vote
      4
      down vote










      up vote
      4
      down vote









      You can bind to the function the index where it is in the array so you can use this index to get and call the next function:






      var funcArray = [func1, func2];
      var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

      boundFuncArray[0]();

      function func1(nextFunctionIndex)
      console.log('func1 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();


      function func2(nextFunctionIndex)
      console.log('func2 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();





      As T.J Crowder stated in the comment below, you can also bind the next function to the current one:






      var funcArray = [func1, func2];
      var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

      boundFuncArray[0]();

      function func1(nextFunc)
      console.log('func1 called');
      // Execute next function:
      nextFunc && nextFunc();


      function func2(nextFunc )
      console.log('func2 called');
      // Execute next function:
      nextFunc && nextFunc();








      share|improve this answer














      You can bind to the function the index where it is in the array so you can use this index to get and call the next function:






      var funcArray = [func1, func2];
      var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

      boundFuncArray[0]();

      function func1(nextFunctionIndex)
      console.log('func1 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();


      function func2(nextFunctionIndex)
      console.log('func2 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();





      As T.J Crowder stated in the comment below, you can also bind the next function to the current one:






      var funcArray = [func1, func2];
      var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

      boundFuncArray[0]();

      function func1(nextFunc)
      console.log('func1 called');
      // Execute next function:
      nextFunc && nextFunc();


      function func2(nextFunc )
      console.log('func2 called');
      // Execute next function:
      nextFunc && nextFunc();








      var funcArray = [func1, func2];
      var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

      boundFuncArray[0]();

      function func1(nextFunctionIndex)
      console.log('func1 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();


      function func2(nextFunctionIndex)
      console.log('func2 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();





      var funcArray = [func1, func2];
      var boundFuncArray = funcArray.map((f, i) => f.bind(null, i));

      boundFuncArray[0]();

      function func1(nextFunctionIndex)
      console.log('func1 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();


      function func2(nextFunctionIndex)
      console.log('func2 called');
      // Execute next function:
      var nextFunc = boundFuncArray[nextFunctionIndex + 1];
      nextFunc && nextFunc();





      var funcArray = [func1, func2];
      var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

      boundFuncArray[0]();

      function func1(nextFunc)
      console.log('func1 called');
      // Execute next function:
      nextFunc && nextFunc();


      function func2(nextFunc )
      console.log('func2 called');
      // Execute next function:
      nextFunc && nextFunc();





      var funcArray = [func1, func2];
      var boundFuncArray= funcArray.map((f, i, arr) => f.bind(null, arr[i + 1]));

      boundFuncArray[0]();

      function func1(nextFunc)
      console.log('func1 called');
      // Execute next function:
      nextFunc && nextFunc();


      function func2(nextFunc )
      console.log('func2 called');
      // Execute next function:
      nextFunc && nextFunc();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 14 at 6:19

























      answered Aug 13 at 12:53









      Faly

      10.2k1821




      10.2k1821







      • 1




        Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
        – T.J. Crowder
        Aug 13 at 13:02






      • 1




        bound, not binded
        – birdspider
        Aug 13 at 16:16












      • 1




        Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
        – T.J. Crowder
        Aug 13 at 13:02






      • 1




        bound, not binded
        – birdspider
        Aug 13 at 16:16







      1




      1




      Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
      – T.J. Crowder
      Aug 13 at 13:02




      Would be better to just bind the next function to it. Then the functions don't need to close over funcArray.
      – T.J. Crowder
      Aug 13 at 13:02




      1




      1




      bound, not binded
      – birdspider
      Aug 13 at 16:16




      bound, not binded
      – birdspider
      Aug 13 at 16:16










      up vote
      3
      down vote













      You can get the current function's name with arguments.callee.name, loop through the array of functions, and call the next function:






      funcArray = [func1, func2, func3];

      // Only func1() and func2() will be documented since the others have repeating code

      function func1()
      // show the current function name
      console.log(arguments.callee.name);

      // loop the array of functions
      for(var i = 0; i < funcArray.length; ++i)

      // when the current array item is our current function name and
      // another function exists after this then call it and break
      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func2()
      console.log(arguments.callee.name);

      // some logic which switches our next function to be func4()
      funcArray[2] = func4;

      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func3()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func4()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      // call the first function
      funcArray[0]();





      Output:



      func1
      func2
      func4





      share|improve this answer






















      • Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
        – Kroltan
        Aug 13 at 13:32










      • @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
        – MonkeyZeus
        Aug 13 at 13:37






      • 1




        @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
        – Sam
        Aug 14 at 7:50











      • I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
        – MonkeyZeus
        Aug 14 at 12:05














      up vote
      3
      down vote













      You can get the current function's name with arguments.callee.name, loop through the array of functions, and call the next function:






      funcArray = [func1, func2, func3];

      // Only func1() and func2() will be documented since the others have repeating code

      function func1()
      // show the current function name
      console.log(arguments.callee.name);

      // loop the array of functions
      for(var i = 0; i < funcArray.length; ++i)

      // when the current array item is our current function name and
      // another function exists after this then call it and break
      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func2()
      console.log(arguments.callee.name);

      // some logic which switches our next function to be func4()
      funcArray[2] = func4;

      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func3()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func4()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      // call the first function
      funcArray[0]();





      Output:



      func1
      func2
      func4





      share|improve this answer






















      • Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
        – Kroltan
        Aug 13 at 13:32










      • @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
        – MonkeyZeus
        Aug 13 at 13:37






      • 1




        @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
        – Sam
        Aug 14 at 7:50











      • I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
        – MonkeyZeus
        Aug 14 at 12:05












      up vote
      3
      down vote










      up vote
      3
      down vote









      You can get the current function's name with arguments.callee.name, loop through the array of functions, and call the next function:






      funcArray = [func1, func2, func3];

      // Only func1() and func2() will be documented since the others have repeating code

      function func1()
      // show the current function name
      console.log(arguments.callee.name);

      // loop the array of functions
      for(var i = 0; i < funcArray.length; ++i)

      // when the current array item is our current function name and
      // another function exists after this then call it and break
      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func2()
      console.log(arguments.callee.name);

      // some logic which switches our next function to be func4()
      funcArray[2] = func4;

      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func3()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func4()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      // call the first function
      funcArray[0]();





      Output:



      func1
      func2
      func4





      share|improve this answer














      You can get the current function's name with arguments.callee.name, loop through the array of functions, and call the next function:






      funcArray = [func1, func2, func3];

      // Only func1() and func2() will be documented since the others have repeating code

      function func1()
      // show the current function name
      console.log(arguments.callee.name);

      // loop the array of functions
      for(var i = 0; i < funcArray.length; ++i)

      // when the current array item is our current function name and
      // another function exists after this then call it and break
      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func2()
      console.log(arguments.callee.name);

      // some logic which switches our next function to be func4()
      funcArray[2] = func4;

      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func3()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func4()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      // call the first function
      funcArray[0]();





      Output:



      func1
      func2
      func4





      funcArray = [func1, func2, func3];

      // Only func1() and func2() will be documented since the others have repeating code

      function func1()
      // show the current function name
      console.log(arguments.callee.name);

      // loop the array of functions
      for(var i = 0; i < funcArray.length; ++i)

      // when the current array item is our current function name and
      // another function exists after this then call it and break
      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func2()
      console.log(arguments.callee.name);

      // some logic which switches our next function to be func4()
      funcArray[2] = func4;

      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func3()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func4()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      // call the first function
      funcArray[0]();





      funcArray = [func1, func2, func3];

      // Only func1() and func2() will be documented since the others have repeating code

      function func1()
      // show the current function name
      console.log(arguments.callee.name);

      // loop the array of functions
      for(var i = 0; i < funcArray.length; ++i)

      // when the current array item is our current function name and
      // another function exists after this then call it and break
      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func2()
      console.log(arguments.callee.name);

      // some logic which switches our next function to be func4()
      funcArray[2] = func4;

      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func3()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      function func4()
      console.log(arguments.callee.name);
      for(var i = 0; i < funcArray.length; ++i)

      if(funcArray[i] === arguments.callee && funcArray[i+1])

      funcArray[i+1]();
      break;




      // call the first function
      funcArray[0]();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 13 at 13:36

























      answered Aug 13 at 13:15









      MonkeyZeus

      11.9k22052




      11.9k22052











      • Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
        – Kroltan
        Aug 13 at 13:32










      • @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
        – MonkeyZeus
        Aug 13 at 13:37






      • 1




        @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
        – Sam
        Aug 14 at 7:50











      • I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
        – MonkeyZeus
        Aug 14 at 12:05
















      • Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
        – Kroltan
        Aug 13 at 13:32










      • @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
        – MonkeyZeus
        Aug 13 at 13:37






      • 1




        @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
        – Sam
        Aug 14 at 7:50











      • I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
        – MonkeyZeus
        Aug 14 at 12:05















      Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
      – Kroltan
      Aug 13 at 13:32




      Havent even checked if this works, but either way, if you are using the name just for comparison, you can compare functions directly. Which will work much more reliably in minified/postprocessed environments.
      – Kroltan
      Aug 13 at 13:32












      @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
      – MonkeyZeus
      Aug 13 at 13:37




      @Kroltan Thanks for the suggestion, looks like it works in pure JS so I updated my answer. Not sure why my answer is still getting downvoted though; it works :/
      – MonkeyZeus
      Aug 13 at 13:37




      1




      1




      @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
      – Sam
      Aug 14 at 7:50





      @MonkeyZeus I upvoted your answer and is the simple solution I tried but failed to get function equality for a mistake. It most certainly works. I had probably not worded by question properly and the accepted answer does provide another approach too for the question asked earlier.
      – Sam
      Aug 14 at 7:50













      I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
      – MonkeyZeus
      Aug 14 at 12:05




      I appreciate it. Your question is certainly a bit vague but a fun challenge nevertheless so I just wanted to provide a solution which others didn't. I think that the answer you accepted is the right way to go in general because it allows your code to be DRY.
      – MonkeyZeus
      Aug 14 at 12:05










      up vote
      0
      down vote













      I dont know if your functions require certain parameters but this is the first thing that came to my mind.






      var functArray = [
      function()
      console.log("function1 executed");
      ,
      function()
      console.log("function2 executed");
      ,
      function()
      console.log("function3 executed");
      ,
      function()
      console.log("function4 executed");
      ];

      functArray.forEach(function(x)
      x();
      );








      share|improve this answer
























        up vote
        0
        down vote













        I dont know if your functions require certain parameters but this is the first thing that came to my mind.






        var functArray = [
        function()
        console.log("function1 executed");
        ,
        function()
        console.log("function2 executed");
        ,
        function()
        console.log("function3 executed");
        ,
        function()
        console.log("function4 executed");
        ];

        functArray.forEach(function(x)
        x();
        );








        share|improve this answer






















          up vote
          0
          down vote










          up vote
          0
          down vote









          I dont know if your functions require certain parameters but this is the first thing that came to my mind.






          var functArray = [
          function()
          console.log("function1 executed");
          ,
          function()
          console.log("function2 executed");
          ,
          function()
          console.log("function3 executed");
          ,
          function()
          console.log("function4 executed");
          ];

          functArray.forEach(function(x)
          x();
          );








          share|improve this answer












          I dont know if your functions require certain parameters but this is the first thing that came to my mind.






          var functArray = [
          function()
          console.log("function1 executed");
          ,
          function()
          console.log("function2 executed");
          ,
          function()
          console.log("function3 executed");
          ,
          function()
          console.log("function4 executed");
          ];

          functArray.forEach(function(x)
          x();
          );








          var functArray = [
          function()
          console.log("function1 executed");
          ,
          function()
          console.log("function2 executed");
          ,
          function()
          console.log("function3 executed");
          ,
          function()
          console.log("function4 executed");
          ];

          functArray.forEach(function(x)
          x();
          );





          var functArray = [
          function()
          console.log("function1 executed");
          ,
          function()
          console.log("function2 executed");
          ,
          function()
          console.log("function3 executed");
          ,
          function()
          console.log("function4 executed");
          ];

          functArray.forEach(function(x)
          x();
          );






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 13 at 22:42









          Fabian Gonzalez

          293




          293




















              up vote
              0
              down vote













              The accepted answer and other comments did help me, but the way I implemented it is as follows:



              //The functions are defined as variables. 
              //They do not get hoisted, so must be defined first.
              func1 = function (arg1, arg2)
              //Code to do whatever...
              ...
              //Execute the next function.
              //The name of the function is returned by executing nextFunc()
              global[nextFunc()](arg1, arg2, arg3);


              func2 = function (arg1) //Note different type of args
              ...


              //Note that this is an array of strings representing function names.
              funcArray = ["func1", "func2", "func3",...]

              //Start the execution...
              func1(arg1, arg2);

              function nextFunc()
              var currentFuncName = nextFunc.caller.name;
              var index = funcArray.indexOf(currentFuncName);
              if (index < funcArray.length)
              return funcArray[index+1];



              The sequence of functions to be executed is easily managed through the array funcArray. The number or type of arguments is not fixed for each function. Additionally, the functions control if they should stop the chain or continue with the next function.



              It is very simple to understand requiring basic Javascript skills. No overheads of using Promises.



              "global" gets replaced by "window" for browser. This is a Node.js implementation. The use of function names in the array will, however, break if you minify the JS code. As I am going to use it on the server, I do not expect to minify it.






              share|improve this answer


























                up vote
                0
                down vote













                The accepted answer and other comments did help me, but the way I implemented it is as follows:



                //The functions are defined as variables. 
                //They do not get hoisted, so must be defined first.
                func1 = function (arg1, arg2)
                //Code to do whatever...
                ...
                //Execute the next function.
                //The name of the function is returned by executing nextFunc()
                global[nextFunc()](arg1, arg2, arg3);


                func2 = function (arg1) //Note different type of args
                ...


                //Note that this is an array of strings representing function names.
                funcArray = ["func1", "func2", "func3",...]

                //Start the execution...
                func1(arg1, arg2);

                function nextFunc()
                var currentFuncName = nextFunc.caller.name;
                var index = funcArray.indexOf(currentFuncName);
                if (index < funcArray.length)
                return funcArray[index+1];



                The sequence of functions to be executed is easily managed through the array funcArray. The number or type of arguments is not fixed for each function. Additionally, the functions control if they should stop the chain or continue with the next function.



                It is very simple to understand requiring basic Javascript skills. No overheads of using Promises.



                "global" gets replaced by "window" for browser. This is a Node.js implementation. The use of function names in the array will, however, break if you minify the JS code. As I am going to use it on the server, I do not expect to minify it.






                share|improve this answer
























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  The accepted answer and other comments did help me, but the way I implemented it is as follows:



                  //The functions are defined as variables. 
                  //They do not get hoisted, so must be defined first.
                  func1 = function (arg1, arg2)
                  //Code to do whatever...
                  ...
                  //Execute the next function.
                  //The name of the function is returned by executing nextFunc()
                  global[nextFunc()](arg1, arg2, arg3);


                  func2 = function (arg1) //Note different type of args
                  ...


                  //Note that this is an array of strings representing function names.
                  funcArray = ["func1", "func2", "func3",...]

                  //Start the execution...
                  func1(arg1, arg2);

                  function nextFunc()
                  var currentFuncName = nextFunc.caller.name;
                  var index = funcArray.indexOf(currentFuncName);
                  if (index < funcArray.length)
                  return funcArray[index+1];



                  The sequence of functions to be executed is easily managed through the array funcArray. The number or type of arguments is not fixed for each function. Additionally, the functions control if they should stop the chain or continue with the next function.



                  It is very simple to understand requiring basic Javascript skills. No overheads of using Promises.



                  "global" gets replaced by "window" for browser. This is a Node.js implementation. The use of function names in the array will, however, break if you minify the JS code. As I am going to use it on the server, I do not expect to minify it.






                  share|improve this answer














                  The accepted answer and other comments did help me, but the way I implemented it is as follows:



                  //The functions are defined as variables. 
                  //They do not get hoisted, so must be defined first.
                  func1 = function (arg1, arg2)
                  //Code to do whatever...
                  ...
                  //Execute the next function.
                  //The name of the function is returned by executing nextFunc()
                  global[nextFunc()](arg1, arg2, arg3);


                  func2 = function (arg1) //Note different type of args
                  ...


                  //Note that this is an array of strings representing function names.
                  funcArray = ["func1", "func2", "func3",...]

                  //Start the execution...
                  func1(arg1, arg2);

                  function nextFunc()
                  var currentFuncName = nextFunc.caller.name;
                  var index = funcArray.indexOf(currentFuncName);
                  if (index < funcArray.length)
                  return funcArray[index+1];



                  The sequence of functions to be executed is easily managed through the array funcArray. The number or type of arguments is not fixed for each function. Additionally, the functions control if they should stop the chain or continue with the next function.



                  It is very simple to understand requiring basic Javascript skills. No overheads of using Promises.



                  "global" gets replaced by "window" for browser. This is a Node.js implementation. The use of function names in the array will, however, break if you minify the JS code. As I am going to use it on the server, I do not expect to minify it.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 19 at 6:08

























                  answered Aug 15 at 18:27









                  Sam

                  1,94132251




                  1,94132251



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51822513%2fin-javascript-how-to-execute-next-function-from-an-array-of-functions%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Popular posts from this blog

                      How to check contact read email or not when send email to Individual?

                      Bahrain

                      Postfix configuration issue with fips on centos 7; mailgun relay