It depends upon how user.login()
is designed to work. If it is designed such that the third argument is a callback function that will be called when the login is complete, you would use the first form (and you would probably have to check an err
argument sent to the callback).
If user.login()
is designed to return a promise that will be fulfilled when the login is complete, then you would use the second form (and you probably want to add an error handler callback).
If it is designed to have both behaviors (always return a promise and call a callback if it is passed), then you can select either method.
If user.login()
is designed such that either will work, then the second structure with the promise is much more extensible because you can take advantage of many of the advantages of promises:
- Easier to chain/sequence multiple async operations.
- Throw-safe in the callback
- Easier to coordinate this async operation with other async operations using things like
Promise.all()
.
- More robust error handling - errors will propagate up in promises, but not in callbacks.
If you've ever written code with a whole bunch of async operations in it, some of which are sequential, some of which are parallel and some of which have to be coordinated with some of the others and this code needs to have robust error handling (such as in a server environment), you will very, very quickly find that promises make it many times easier to accomplish your goal. And, once you learn them, you will find they are even preferred for the simple situations too.
If you've ever written code where you need to carry out a bunch of async operations and you need to operate on all the returned data when all the async operations are done, promises make this trivial to code. Without promises, you have to write a lot of scaffolding code yourself to keep track of the data and keep track of when everything is done and somehow propagate errors if any occur.