2016-11-05 39 views
-1

我想创建一个函数,如果该参数不存在,将调用另一个函数。我将如何使用异步函数作为另一个函数的默认参数

例如:

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 
} 
+0

为什么不把它分成多个功能? – afuous

+0

没有真正的理由,只是想看看是否有办法使这项工作。将它分成两个功能将更加清晰,并解决问题,但我想学习新的东西。 –

+0

我不认为这很符合默认参数。你必须用['arguments'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)以旧式的方式来完成。 – afuous

回答

1

尝试用JS无极来包装异步函数,并在相关的函数调用其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 
    }); 
} 
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(); 
    } 
} 
+0

如果'getAllFoo'是异步的,这不起作用。 – afuous

+0

抱歉没有得到你一开始想要做的事......为什么不只是使用承诺? – marcinrek

+0

我同意;不是我的问题。 – afuous

0

你想包异步功能在承诺。

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 
    )} 
相关问题