-1

I am trying to make a function that will call another function if the parameter doesn't exist.

For example:

function getAllFoo(){
    // makes a request to an api and returns an array of all foos
}

function getNumFoo(foosArray = getAllFoo(), num = 5){
    // selects num of foos from foosArray or calls getAllFoos then selects num of them
}
  • Why not just split it into multiple functions? – afuous Nov 05 '16 at 19:52
  • No real reason beyond just wanting to see if there was a way to make this work. Splitting it into two functions would be more clear, as well as solve the issue, but I wanted to learn something new. – Jonathan Case Nov 05 '16 at 19:58
  • I don't think this really fits well with default parameters. You would have to do it the old fashioned way with [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments). – afuous Nov 05 '16 at 20:02

3 Answers3

1

try to wrap your asynchronous function with JS Promise, and in your dependent function call its then() function:

function getAllFoo () {
  return new Promise(
    // The resolver function is called with the ability to resolve or
    // reject the promise
    function(resolve, reject) {
      // resolve or reject here, according to your logic
      var foosArray = ['your', 'array'];
      resolve(foosArray);
    }
  )
};

function getNumFoo(num = 5){
  getAllFoo().then(function (foosArray) {
    // selects num of foos from foosArray or calls getAllFoos then selects num of them
  });
}
Andriy
  • 14,781
  • 4
  • 46
  • 50
0
function getAllFoo(){
    // makes a request to an api and returns an array of all foos
}

function getNumFoo(foosArray = getAllFoo(), num = 5){
    // Call getAllFoo() when num is not passed to this function
    if (undefined === num) {
        getAllFoo();
    }
}
marcinrek
  • 339
  • 1
  • 8
0

You would wrap the async function in a promise.

    function promiseGetNumFoo(num) {
      return new Promise((resolve, reject) =>
        // If there's an error, reject; otherwise resolve
        if(err) {
          num = 5;
        } else {
          num = resolve(result);
      ).then((num) =>
        // your code here
    )}
zyam
  • 11
  • 2