How to do error handling for rejected promise individually in PromiseManyArray

Hello guys,

I am trying to get comments data from posts, but having trouble getting the data

So when I try to get the comments data, and if there is an invalid comment in the post, Promise is rejected (comments API returns a 404 error), and the app breaks


const post = await this.store.findRecord('post',1)

let totalLikes = 0

//post.get('comments') : return type -> PromiseManyArray

const comments = await post.get('comments').forEach(comment=>{
    console.log(comment.title)
    totalLikes += comment.likes 
  //Some code
})

Here I am trying to get the title or find the total likes for all the comments, so when trying to run the above code, there are 20 comments in a post, and while fetching data for 20 comments, if one comment return 404, and promise is rejected, then the whole function breaks

  • Is there a way to find the total count of likes, only fulfilled Promise excluding the rejected Promise
  • How to do error handling for a single rejected promise I am not able to add a try-catch block for comments individually

posts give comments id, in their response

{
"data": {
        "id": "7788",
        "type": "post",
        "attributes": {
            "title": "SOME POST",
             ...
        },
        "relationships": {
            "comments": {
                "data": [
                    {
                        "type": "comment",
                        "id": "4648"  -> this may be invalid
                    },
                    {
                        "type": "comment",
                        "id": "6599"
                    },
                    ...
                ]}
        }
}

Ember: 4.11 Ember Data: 4.7

I think ideally you would implement the post->comments lookup in the adapter as a query operation (“return all comments where post_id is X”) rather than make 1 request per comment, since that simple approach doesn’t scale (popular posts will cause your own app to execute denial of service attacks on your backend). A backend’s query implementation should naturally just omit missing/deleted comments in the returned array. The query approach can more easily incorporate pagination into the data model, too (“give me the Nth batch of X comments where post_id is Y”), helping you maintain performance.

Another approach is to pass an adapter option to include the comments as you reload the record. This assumes your backend will do the same as above, querying for related comments rather than doing 1:1 fetch by id, but can also lead to poor responsiveness for popular posts, since “give me this post and all its comments” doesn’t lend well to pagination.