面试题答案
一键面试- 处理Promise的拒绝情况:
- 链式调用
.catch
:在Promise链的最后添加.catch
块,捕获整个链中任何Promise的拒绝。
const asyncOperation1 = () => { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Operation 1 failed')); }, 1000); }); }; const asyncOperation2 = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve('Operation 2 success'); }, 1000); }); }; asyncOperation1() .then(result => { console.log(result); }) .then(() => asyncOperation2()) .catch(error => { console.error('Caught error:', error.message); });
try...catch
包裹async/await
:在async
函数中使用try...catch
块。
const asyncFunction = async () => { try { await asyncOperation1(); await asyncOperation2(); } catch (error) { console.error('Caught error:', error.message); } }; asyncFunction();
- 链式调用
- 区分正常的拒绝处理和未处理的拒绝场景:
- 正常的拒绝处理:当在
.catch
块或try...catch
块中捕获到拒绝时,属于正常处理。代码如下:
const promise1 = new Promise((resolve, reject) => { reject(new Error('Normal rejection')); }); promise1.catch(error => { console.log('Normal rejection handled:', error.message); });
- 未处理的拒绝场景:如果没有为Promise添加
.catch
块,并且在async
函数中没有使用try...catch
块,Node.js会发出unhandledRejection
事件。
const promise2 = new Promise((resolve, reject) => { reject(new Error('Unhandled rejection')); }); process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason.message); });
- 正常的拒绝处理:当在
通过在Promise链中恰当使用.catch
以及在async
函数中使用try...catch
来处理拒绝,同时通过process.on('unhandledRejection')
来捕获未处理的拒绝,这样可以有效避免未处理的拒绝错误导致程序崩溃。