KrNel
KrNel

Reputation: 434

Promise not resolving to value when returned

I have a recursive function that resolve a mapped array correctly recursively.

const postCommentsRecursive = (author, permlink) => {
  return client.database.call('get_content_replies', [author, permlink])
    .then(replies => Promise.all(replies.map(r => {
      if (r.children > 0) {
        return postCommentsRecursive(r.author, r.permlink)
          .then(children => {
            r.replies = children;
            return r;
          })
      }else {
        return r;
      }
    })))
}

But when I added another data fetch, the return from then stays a promise:

const postCommentsRecursive = (author, permlink) => {
  return client.database.call('get_content_replies', [author, permlink])
    .then(replies => Promise.all(replies.map(r => {
//NEW CODE START
      const votes = client.database
        .call('get_active_votes', [r.author, r.permlink])
        .then(av => {
          return av;
        });
      r['active_votes'] = votes;
//NEW CODE END
      if (r.children > 0) {
        return postCommentsRecursive(r.author, r.permlink)
          .then(children => {
            r.replies = children;
            return r;
          })
      }else {
        return r;
      }
    })))
}

av is the array value, great. But when I add it to the object from votes, it is a Promise instead.

Each replies child object is still resolved as a value, but inside each r when I add votes to r as r['active_votes'] = votes, the value set in the object is a Promise {<resolved>: Array(1)}.

enter image description here

I can't figure out how to get the actual Array(1) as a value, not the Promise as a value. How do I just get the Array as a value, and not the Promise?

Thank you!

Upvotes: 0

Views: 53

Answers (1)

klhr
klhr

Reputation: 3380

In your code, you're assigning r.votes to be a Promise. Instead, you need to go into the .then of that promise if you want to mutate r. (Conceptually, it's the same as what you're doing in the r.children > 0 block)

      return client.database
        .call('get_active_votes', [r.author, r.permlink])
        .then(av => {
          // mutate r
          r.active_votes = av;
          // now return it so that this entire promise resolves with `r`
          return r;
        });

async/await generally makes code like this a little clearer:

r.active_votes = await client.database
        .call('get_active_votes', [r.author, r.permlink])

Upvotes: 1

Related Questions