Promise.resolve(5) .then(value => { console.log(value); return value * 2; }) .then(value => { throw new Error('Oops'); }) .catch(error => { console.log('Error caught:', error.message); return 10; }) .then(value => { console.log('Final value:', value); });
The first then logs 5 and returns 10. The second then throws an error. The catch catches it and logs the error message, then returns 10. The final then logs 'Final value: 10'.
Promise.reject('Failed') .then(() => { console.log('Success'); });
The Promise rejects but there is no catch to handle it, so the error is unhandled and logged as 'Uncaught (in promise) Failed'.
async function test() { try { await Promise.reject('Error!'); } catch (e) { console.log('Caught:', e); } console.log('Done'); } test();
The await rejects, so control goes to catch which logs the error. Then the function continues and logs 'Done'.
function getData() { return new Promise((resolve, reject) => { reject('Network error'); }); } getData() .then(data => console.log('Data:', data)) // Error handling here ;
The catch method handles rejected Promises. Option C looks similar but the second argument to then is less common and can cause confusion.
Promise.resolve('Start') .then(value => { console.log(value); return Promise.reject('Fail'); }) .catch(error => { console.log('Caught:', error); return 'Recovered'; }) .then(value => { console.log(value); throw new Error('Crash'); }) .catch(error => { console.log('Final catch:', error.message); });
The first then logs 'Start' and rejects with 'Fail'. The first catch logs 'Caught: Fail' and returns 'Recovered'. The next then logs 'Recovered' and throws 'Crash'. The final catch logs 'Final catch: Crash'.