Jonathan Case Jonathan Case - 29 days ago 5
Javascript Question

How would I use an asynchronous function as a default parameter for another function

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
}

Answer

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
  });
}
Comments