面试题答案
一键面试基本步骤
- 定义异步任务函数:使用
async
关键字定义异步函数,函数内部使用await
等待Promise
的结果。这些异步函数通常会返回Promise
,例如读取文件内容的函数readFileAsync
。 - 创建
Promise
数组:将多个异步任务函数调用(每个调用返回一个Promise
)组成一个数组。 - 使用
Promise.all
:将这个Promise
数组作为参数传递给Promise.all
,Promise.all
会等待所有的Promise
都完成(或有一个Promise
被拒绝)。 - 处理结果:在
async
函数中使用await
等待Promise.all
的结果,得到所有异步任务的结果数组,然后可以对结果进行处理。
示例代码
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
// 定义异步读取文件的函数
const readFileAsync = promisify(fs.readFile);
async function readFilesConcurrently(filePaths) {
const promises = filePaths.map(filePath => readFileAsync(path.join(__dirname, filePath), 'utf8'));
try {
const results = await Promise.all(promises);
results.forEach((result, index) => {
console.log(`File ${filePaths[index]} content:`, result);
});
return results;
} catch (error) {
console.error('An error occurred:', error);
}
}
// 调用函数并传入文件路径数组
const filePaths = ['file1.txt', 'file2.txt', 'file3.txt'];
readFilesConcurrently(filePaths);
上述代码中,readFileAsync
使用promisify
将fs.readFile
转换为返回Promise
的函数。readFilesConcurrently
函数接收一个文件路径数组,创建一个包含所有文件读取Promise
的数组,使用Promise.all
并发处理这些Promise
,并在所有读取操作完成后处理结果。如果有任何一个读取操作失败,Promise.all
会被拒绝并进入catch
块。