简体   繁体   中英

Getting grand children of an instance

I have associations set up so that a Category has many Posts and each Post has many Comments:

CategoryPostComment

Having an instance of Category , how do one get all comments ?

I've tried this:

const posts = await category.getPosts()
const comments = await posts.map(post => post.getComments())

But the returned comments is only an array of Promises :

[ Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined },
  ...

If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.

This is what happening in your case. posts.map retruns an array which is not promise and hence await is resolving with the array of promises.

const posts = await category.getPosts()
const comments = await posts.map(post => post.getComments())

In the above logic posts.map is returning an array but not a promise. so to make it work you need to wrap that map in a Promise.all.

const posts = await category.getPosts()
const comments = await Promise.all(posts.map(post => post.getComments()))

Now when we print comments it will display array of the responses from all the resolved promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM