0

Is Better to use .catch in end of my Code or normal try/catch?
Can you Explain it.

Example 1:

User.findOne({ _id: 444, User })
    .then(obj => {
        console.log(obj.inviteCount);
        return (obj.inviteCount);
    }).catch(err => console.log(err));

Example 2:

try{
 User.findOne({ _id: 444, User })
        .then(obj => {
            console.log(obj.inviteCount);
            return (obj.inviteCount);
        })
}
catch(err) {
console.log(err)
}
Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103
  • 1
    Example 2 won't actually work. Errors in promises are delivered via a promise rejection, which can only be captured using a `.catch`. So your second examples `catch` statement would never be triggered. – CRice Oct 27 '17 at 19:31
  • Possible duplicate of [Catching Errors in JavaScript Promises with a First Level try ... catch](https://stackoverflow.com/questions/24977516/catching-errors-in-javascript-promises-with-a-first-level-try-catch) – Martin Adámek Oct 27 '17 at 19:33
  • I Don't undestand very well because of my bad english, Can you Explain it and write me an example? and how can i use try catch in secend example? – Saeed Heidarizarei Oct 27 '17 at 19:34

1 Answers1

1

Promise rejection is asynchronous, using try/catch block you can catch only synchronous error.

You could use new async/await syntax and compile via babel or something (depends on where you wanna run your code).

async/await example (working in node v8+)

try {
    const obj = await User.findOne({ _id: 444, User });
    console.log(obj.inviteCount);

    return obj.inviteCount;
} catch(err) {
    console.log(err);
}

Or you could use bluebird's Promise.coroutine (working in node 6+):

// load bluebird first, so the `Promise` object is monkey patched
// or in node use `const Promise = require('bluebird');`
Promise.coroutine(function*() { 
    try {
        const obj = yield User.findOne({ _id: 444, User });
        console.log(obj.inviteCount);

        return obj.inviteCount;
    } catch (e) {
        console.log(err);
    }
})();
Martin Adámek
  • 16,771
  • 5
  • 45
  • 64