Hi,

On Wednesday, September 6, 2017 at 4:15:19 PM UTC+2, Rohan Pota wrote:
>
>
>  1. How does `Promise.all()` work ?
>

Promise.all 
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all>works
 
like this: you give it *an array* of promises, and it returns a *single 
promise* that is resolved when all the initial promises are done.
Meaning, in a case like this:

    Promise.all([p1, p2, p3, ..., pn])
      .then(handlerFuinction)
      .catch(errorHandlerFunction);

In the example above, you give a handler (callback), but it won't get 
called until ALL of the p1, p2, p3.. are resolved.
If *any* of the promises fails or throws, your entire chain will get 
canceled. Now be careful here, some of the promises may have been resolved 
already (e.g. updated stuff in db), while others are still in progress, so 
you might have to do some cleanup call in the .catch handler.

In your case, you first have a promise to be something of this:

    req.payload ? User.findById(req.payload.id) : null,

So if a call to this endpoint was authenticated (I assume that's wath 
auth.optional does), we get a User.findById(), otherwise we just get *null* 
(without 
going to db).
So in any case, your first promise will either return a user object or it 
will return *null*.

Your second promise is that execPopulate() promise.

Now, *when both of these* are done (both getting the user and populating 
that article), your last handler gets called. But if any of those fails 
(e.g. the database is down or the network breaks or whatever)

 

>  2. Why do we need to repopulate author field in `router.get()` method 
> when already did that in the `router.param()` method?
>

Well, I can't tell easily without looking in the code, but it looks like 
you can take out the second call to populate. That'd be the second promise 
in your Promise.all array. You could also skip the router.param up there 
completely, but you may be using that somewhere later on the router, so 
make sure it all works without it if you go that route (no pun intended :)).

 

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to nodejs+unsubscr...@googlegroups.com.
To post to this group, send email to nodejs@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/5173d1d1-f81e-4522-9fe7-d990f847e5de%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to