img

【JavaScript】手把手教你写高质量 JavaScript 异步代码!

2022-11-29 0条评论 1.4k次阅读 JavaScript


前言

分享几个我平时写异步代码的小技巧以及我之前看到过得一些不好的写法。

手把手教程

reject一个Error对象

reject Promise时强制使用Error对象,方便浏览器底层更容易的分配堆栈以及查找堆栈。

// bad
Promise.reject('error reason');

// good
Promise.reject(new Error('error reason'))

不要在Promise上使用async

不要把async函数传递给Promise构造函数,因为没有必要,其次如果async函数异常,那么你的promise并不会reject

// bad
new Promise(async (resolve, reject) => {})

// good
new Promise((resolve, reject) => { async function(){coding....}()})

不要使用await在循环中

尽可能将这写异步的任务改为并发,可以大幅提高代码执行效率

// bad
for(const apiPath of paths) {
    const { data } = await request(apiPath)
}

// good
const results = []
for(const apiPath of paths) {
    const res = resquest(apiPath)
    results.push(res)
}
await Promise.all(results)

不要再Promise中使用return语句

// bad
new Promise((resolve, reject) => {
    if(isOK) return 'ok'
    return 'not ok'
})
// good
new Promise((resolve, reject) => {
    if(isOK) resolve('ok')
    reject(new Error('not ok'))
})

防止回调地狱

// bad
p1((err, res1) => {
    p2(res1, (err, res2) => {
        p3(res2, (err, res3) => {
            p4(res3, (err, res4) => {
                console.log(res4)
            })
        })
    })
})

// good
const res1 = await p1()
const res2 = await p1(res1)
const res3 = await p1(res2)
const res4 = await p1(res3)
console.log(res4)

别忘了异常处理

Promise

// bad
asyncPromise().then(() => {})

// good
asyncPromise().then(() => {}).catch(() => {})

async aiwat

// bad
const result = await asyncPromise()

// good
try {
    const result = await asyncPrmise()
} catch() {
    // do something
}

不要awiat一个非Promise函数

// bad
function getUserInfo() {
    return userInfo
}
await getUserInfo()

// good
async function getUserInfo() {
    return userInfo
}
await getUserInfo()

不要将Promise作为判断条件或者参数

async function getUserInfo() {
    return userInfo
}

// bad
if(getUserInfo()) {}

// good
if(await getUserInfo()) {}

// better
const { userInfo } = await getUserInfo()
if(userInfo) {}

往期回顾

本文转自 https://juejin.cn/post/7102240670269571109, 如有侵权,请联系删除。

🏷️ #Promise

💬 COMMENT


🦄 支持markdown语法

👋友