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

时间:2016-11-05 19:48:11

标签: javascript function ecmascript-6 default-parameters

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

例如:

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
}

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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();
    }
}

答案 2 :(得分:0)

您可以将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
    )}