2016-11-05 3 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

この作業を行う方法があるかどうかを見たいと思っただけでは、本当の理由はありません。それを2つの機能に分けることはより明確で問題を解決するだけでなく、新しいことを学びたかったのです。 –

+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 
    )} 
関連する問題