承诺不退还价值

时间:2019-03-26 03:49:41

标签: javascript promise

我有一个递归函数,可以递归地正确解析映射的数组。

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;
      }
    })))
}

但是当我添加另一个数据提取时,then的返回仍然是一个承诺:

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是数组值,很好。但是,当我将其从votes添加到对象时,它是Promise

每个replies子对象仍被解析为值,但是当我在r中将votes作为r添加到r['active_votes'] = votes时,该值集对象中的Promise {<resolved>: Array(1)}

enter image description here

我不知道如何获取实际的Array(1)作为值,而不是Promise作为值。我该如何获取Array而不是Promise的值?

谢谢!

1 个答案:

答案 0 :(得分:1)

在您的代码中,您将r.votes分配为Promise。相反,如果要突变.then,则需要进入该承诺的r。 (从概念上讲,这与您在r.children > 0块中所做的相同)

      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通常使这样的代码更加清晰:

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