0

ok i'm asking this again, why the catch in the following code is not working as expected ? is this a design flaw of js ?

const getUserById = (id, authorized) => {
    return new Promise((resolve, reject) => {
        if (!authorized) {
            reject('Unauthorized access to the user data');
        }
        resolve({
            id: id,
            username: 'admin'
        });
    });
}

try {
    getUserById(10, false)
        .then(user => console.log(user.username));
    // the following code still executes ?
    console.log('next');

} catch (error) {
    console.log(`Caught by try/catch ${error}`);
}

Surprisingly, the catch didn't work.

The theory of try/catch block is catch should be able to caught all issues from try block. If we redesign JavaScript, can we make the catch in above code to work ?

user3552178
  • 2,719
  • 8
  • 40
  • 67
  • 2
    If you had `await`ed the promise, it would work. But if you're not waiting, the promise is rejected *after* the `console.log('next')` code ran and the `try` block was left already. There's no way to catch an asynchronous error synchronously. – Bergi Jul 01 '22 at 02:39
  • "*ok i'm asking this again*" - have you asked it before already? – Bergi Jul 01 '22 at 02:42
  • That's a very good point, thx very much. Yes await can make it work. No i haven't asked it before but others have asked similar ones and the threads have been too complicated. Thx ! – user3552178 Jul 01 '22 at 03:18

0 Answers0