2017-11-03 47 views
0

私は再帰を使用して複数のAPI呼び出しの結果を配列に書き込もうとしています。私はここES6と再帰的なもので私の頭の中ではかなり終わっており、何か助けが必要かもしれません。再帰呼び出しapi(axios/javascript)

getAllEmployees: function() { 
    let allEmployees = []; // this array will contain all employees 
    let pageNumber = 1; // start with page 1 
    const getThoseEmployees = function(pageNumber) { 
     return axios.get(rest_url + 'users/?per_page=50&page=' + pageNumber, { 
      headers: { 
       'X-WP-Nonce': WPsettings.nonce 
      }, 
     }).then(response => { 
      // add the employees of this response to the array 
      allEmployees = allEmployees.concat(response.data); 
      pageNumber++; 
      if (response.headers['x-wp-total'] > allEmployees.length) { 
       // do me again... 
       return getThoseEmployees(pageNumber); 
      } else { 
       // this was the last page, return the collected contacts 
       return allEmployees; 
      } 
     }); 
    } 
    return getThoseEmployees(); 
}, 


// after "created" in vue 
this.allEmployees = this.getAllEmployees(); // returns "promise" 
+1

可能性のある重複した[非同期呼び出しからの応答を返すには?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-呼び出し) – evolutionxbox

答えて

0

はあなたが約束の.thenメソッドを使用しなければならない約束から解決された値にアクセスするには:

はここだけ「約束」を返し、私の現在のコードです。だからではなく、この割り当て、this.allEmployees = this.getAllEmployees();アクセスので、同様getAllEmployeesから解決された値の:

this.getAllEmployees() 
.then(employees => { 
    console.log(employees); // make sure this is what you need 
    this.allEmployees = employees; 
}); 

EDIT:コメントに返信。

あなたの関数getAllEmployeesは、約束しているgetThoseEmployeesの値を返します。最終的に返されるallEmployees.thenの無名関数の内部にあるため、その値は常にgetThoseEmployeesによって返される約束の内部になります。 getDataから私が欲しいフォーマットされたデータにアクセスするために

// This functions return value is a promise 
const getData =() => { 
    return axios.get('some-url') 
    .then(data => { 
     // Anything returned inside of a .then will be 
     // resolved and can only be accessed with another .then. 
     // Using .then itself will return another promise object, 
     // which is why promises can be chained. 
     return formatThisData(data); 
    }); 
}; 

、私は約束から解決されたデータにアクセスする必要があります。

getData() 
.then(formattedData => { 
    // formattedData is what was returned from inside the .then above 
}); 
+0

しかし、関数は最終的にallEmployeesの値を返しませんか? 私はそれについて考えた方法で、getThoseEmployees()は、代わりにallEmployees-arrayを返すelse文まで自身を呼び出します。 –

+1

素晴らしい!私は理解し、それは動作します!ありがとうございました。 –

+0

Dominicsの回答を正しいとマークしました。私の質問に答えてくれたので、私は理解しました。しかし、私は提案された複製(長いスレッド)を読んでいるので、それをさらに明確にすると確信しています。わからない "これが私の問題を解決しました"ボタンをチェックする必要があるかどうか? –

関連する問題