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

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

本文关键字:函数 默认 参数 另一个 何使用 异步      更新时间:2023-09-26

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

例如:

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
}

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

可以将async函数包装在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
    )}