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)

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

相关推荐
qianmoQ20 分钟前
第五章:工程化实践 - 第三节 - Tailwind CSS 大型项目最佳实践
前端·css
椰果uu36 分钟前
前端八股万文总结——JS+ES6
前端·javascript·es6
微wx笑1 小时前
chrome扩展程序如何实现国际化
前端·chrome
~废弃回忆 �༄1 小时前
CSS中伪类选择器
前端·javascript·css·css中伪类选择器
CUIYD_19891 小时前
Chrome 浏览器(版本号49之后)‌解决跨域问题
前端·chrome
IT、木易1 小时前
跟着AI学vue第五章
前端·javascript·vue.js
薛定谔的猫-菜鸟程序员1 小时前
Vue 2全屏滚动动画实战:结合fullpage-vue与animate.css打造炫酷H5页面
前端·css·vue.js
春天姐姐2 小时前
vue3项目开发总结
前端·vue.js·git
谢尔登2 小时前
【React】React 性能优化
前端·react.js·性能优化
来一碗刘肉面2 小时前
TypeScript - 属性修饰符
前端·javascript·typescript