面试题答案
一键面试使用 Promise 和箭头函数实现
function asyncOperation1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('result1');
}, 1000);
});
}
function asyncOperation2(input) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (input) {
resolve('result2 from'+ input);
} else {
reject(new Error('Input is null or undefined'));
}
}, 1000);
});
}
function asyncOperation3(input) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (input) {
resolve('result3 from'+ input);
} else {
reject(new Error('Input is null or undefined'));
}
}, 1000);
});
}
asyncOperation1()
.then(result1 => asyncOperation2(result1))
.then(result2 => asyncOperation3(result2))
.then(finalResult => {
console.log(finalResult);
})
.catch(error => {
console.error('Error:', error.message);
});
在上述代码中,箭头函数在 .then
回调中起到将前一个 Promise 的结果作为参数传递给下一个异步操作函数的作用。在错误捕获方面,.catch
回调使用箭头函数来处理整个链式调用过程中任何一个 Promise 被拒绝时抛出的错误,这样可以集中处理错误,避免在每个异步操作函数内部重复编写错误处理代码。
使用 async/await 实现
async function asyncOperation1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('result1');
}, 1000);
});
}
async function asyncOperation2(input) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (input) {
resolve('result2 from'+ input);
} else {
reject(new Error('Input is null or undefined'));
}
}, 1000);
});
}
async function asyncOperation3(input) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (input) {
resolve('result3 from'+ input);
} else {
reject(new Error('Input is null or undefined'));
}
}, 1000);
});
}
async function main() {
try {
const result1 = await asyncOperation1();
const result2 = await asyncOperation2(result1);
const finalResult = await asyncOperation3(result2);
console.log(finalResult);
} catch (error) {
console.error('Error:', error.message);
}
}
main();
在这个 async/await
的实现中,箭头函数没有直接体现在链式调用中,但 async
函数本质上也是基于箭头函数语法特性的一种异步函数定义方式。try...catch
块用于捕获在 await
操作时可能抛出的错误,这种方式使得错误捕获更加直观和简洁,将错误处理代码集中在一个块中,提高了代码的可读性和维护性。