MST

星途 面试题库

面试题:JavaScript 箭头函数在复杂异步流程中的应用

假设有一个需求,需要依次进行三个异步操作(例如三次网络请求),并且每个操作的结果作为下一个操作的输入。请使用箭头函数结合 Promise 或者 async/await 来实现这个异步流程,并解释代码中箭头函数是如何起到作用的,尤其是在处理错误捕获方面。
13.5万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

使用 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 操作时可能抛出的错误,这种方式使得错误捕获更加直观和简洁,将错误处理代码集中在一个块中,提高了代码的可读性和维护性。