我将如何使用异步函数作为另一个函数的默认参数

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

我正在尝试创建一个函数,如果参数不存在,该函数将调用另一个函数。

例如:

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

尝试用 JS Promise 包装你的异步函数,并在你的依赖函数中调用它的 then() 函数:

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

您可以将异步函数包装在一个 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
    )}