async/await 你可能正在将异步写成同步

前言

你是否察觉到自己随手写的异步函数,实际却是"同步"的效果!

正文

以一个需求为例:获取给定目录下的全部文件,返回所有文件的路径数组。

第一版

思路很简单:读取目录内容,如果是文件,添加进结果数组,如果还是目录,我们递归执行。

js 复制代码
import path from 'node:path'
import fs from 'node:fs/promises'
import { existsSync } from 'node:fs'

async function findFiles(root) {
    if (!existsSync(root)) return
    
    const rootStat = await fs.stat(root)
    if (rootStat.isFile()) return [root]

    const result = []
    const find = async (dir) => {
        const files = await fs.readdir(dir)
        for (let file of files) {
            file = path.resolve(dir, file)
            const stat = await fs.stat(file)
            if (stat.isFile()) {
                result.push(file)
            } else if (stat.isDirectory()) {
                await find(file)
            }
        }
    }
    await find(root)
    return result
}

机智的你是否已经发现了问题?

我们递归查询子目录的过程是不需要等待上一个结果的,但是第 19 行代码,只有查询完一个子目录之后才会查询下一个,显然让并发的异步,变成了顺序的"同步"执行。

那我们去掉 19 行的 await 是不是就可以了,当然不行,这样的话 await find() 在没有完全遍历目录之前就会立刻返回,我们无法拿到正确的结果。

思考一下,怎么修改它呢?......让我们看第二版代码。

第二版

js 复制代码
import path from 'node:path'
import fs from 'node:fs/promises'
import { existsSync } from 'node:fs'

async function findFiles(root) {
    if (!existsSync(root)) return
    
    const rootStat = await fs.stat(root)
    if (rootStat.isFile()) return [root]

    const result = []
    const find = async (dir) => {
        const task = (await fs.readdir(dir)).map(async (file) => {
            file = path.resolve(dir, file)
            const stat = await fs.stat(file)
            if (stat.isFile()) {
                result.push(file)
            } else if (stat.isDirectory()) {
                await find(file)
            }
        })
        return Promise.all(task)
    }
    await find(root)
    return result
}

我们把每个子目录内容的查询作为独立的任务,扔给 Promise.all 执行,就是这个简单的改动,性能得到了质的提升,让我们看看测试,究竟能差多少。

对比测试

js 复制代码
console.time('v1')
const files1 = await findFiles1('D:\\Videos')
console.timeEnd('v1')

console.time('v2')
const files2 = await findFiles2('D:\\Videos')
console.timeEnd('v2')

console.log(files1?.length, files2?.length)

版本二快了三倍不止,如果是并发的接口请求被不小心搞成了顺序执行,差距比这还要夸张。

相关推荐
Fan_web8 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常10 分钟前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇1 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr1 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho2 小时前
【TypeScript】知识点梳理(三)
前端·typescript
安冬的码畜日常3 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
小白学习日记3 小时前
【复习】HTML常用标签<table>
前端·html
丁总学Java4 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele4 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范