How to retrieve all posts of a user via Facebook Graph API using promises and recursion?
<p>I am currently developing a web app which uses the Facebook Graph API.</p>

<p>What I would like to achieve is to get all posts of a user.</p>

<p>However, this is not that easy since I have to paginate the results.</p>

<p>At the moment I am struggeling with promises.</p>

<p>What I try to achieve is to fill an array with the post objects.</p>

<p>Therefore I use promises and recursion which does not work as expected.</p>

<p>My code currently looks as follows:</p>

<pre><code>// Here I retrieve the user with his or her posts,
// just the first 25 due to pagination
if (accessToken) {
  return new Promise(resolve =&gt; {
    FB.api('/me?fields=id,name,posts&amp;access_token=' + accessToken, response =&gt; {
      this.get('currentUser').set('content', response);
      resolve()
    })
  })
}

// Returns all posts of a given user
function getAllPostsOfUser(posts, postsArr) {
  // Process each post of the current pagination level
  for (var post of posts.data) {
    // Only store meaningful posts
    if (post !== undefined &amp;&amp; post.message !== undefined) {
      postsArr.push(post)
    }
  }

  // Further posts are retrievalable via paging.next which is an url
  if (posts.data.length !== 0 &amp;&amp; posts.paging.next !== undefined) {
    FB.api(posts.paging.next, response =&gt; {
      getAllPostsOfUser(response, postsArr)
      resolve()
    })
  }

  return postsArr
}

var posts = getAllPostsOfUser(this.get('currentUser').content.posts, [])
// I want to use all the posts here
console.log(posts)
</code></pre>

<p>The problem I have is that I want to use the posts where the console.log is placed but when I log the posts array a lot of posts are missing.</p>

<p>I am sure that I did something wrong with the promises but I do not know what.</p>

<p>I would be glad if anyone could guide me to a solution.</p>

<p>Thank you in advance.</p>