av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

Async/Await你是會(huì)用,但是你知道怎么處理錯(cuò)誤嗎?

前言

Promise封裝請求

大家平時(shí)如果使用Promise封裝請求,那么當(dāng)你使用這個(gè)請求函數(shù)的時(shí)候是這樣的:

// 封裝請求函數(shù)
const request = (url, params) => {
return new Promise((resolve, reject) => {
// ...do something
})
}

// 使用時(shí)
const handleLogin = () => {
request(
'/basic/login',
{
usename: 'sunshine',
password: '123456'
}
).then(res => {
// success do something
}).catch(err => {
// fail do something
})
}

可以看到,當(dāng)你的請求成功時(shí),會(huì)調(diào)用then方法,當(dāng)你的請求失敗時(shí)會(huì)調(diào)用catch方法。

async/await

Promise的出現(xiàn)解決了很多問題,但是如果請求多了且有順序要求的話,難免又會(huì)出現(xiàn)嵌套的問題,可讀性較差,比如:

const handleLogin = () => {
request(
'/basic/login',
{
usename: 'sunshine',
password: '123456'
}
).then(res => {
// 登錄成功后獲取用戶信息
request(
'/basic/getuserinfo',
res.id
).then(info => {
this.userInfo = info
}).catch()
}).catch(err => {
// fail do something
})

所以這個(gè)時(shí)候async/await出現(xiàn)了,他的作用是:用同步的方式執(zhí)行異步操作,上面的代碼使用async/await的話可以改寫成:

const handleLogin = async () => {
const res = await request('/basic/login', {
usename: 'sunshine',
password: '123456'
})
const info = await request('/basic/getuserinfo', {
id: res.id
})
this.userInfo = info
}

這樣的話代碼的可讀性比較高,而不會(huì)出現(xiàn)剛剛的嵌套問題,但是現(xiàn)在又有一個(gè)問題了,Promise有catch這個(gè)錯(cuò)誤回調(diào)來保證請求錯(cuò)誤后該做什么操作,但是async/await該如何捕獲錯(cuò)誤呢?

async-to-js

其實(shí)已經(jīng)有一個(gè)庫async-to-js已經(jīng)幫我們做了這件事,我們可以看看它是怎么做的,它的源碼只有短短十幾行,我們應(yīng)該讀讀它的源碼,學(xué)學(xué)它的思想

源碼很簡單

/**
* @param { Promise } 傳進(jìn)去的請求函數(shù)
* @param { Object= } errorExt - 拓展錯(cuò)誤對象
* @return { Promise } 返回一個(gè)Promise
*/
export function to(
promise,
errorExt
) {
return promise
.then(data => [null, data])
.catch(err => {
if (errorExt) {
const parsedError = Object.assign({}, err, errorExt)
return [parsedError, undefined]
}

return [err, undefined]
})
}

export default to

源碼總結(jié):to函數(shù)返回一個(gè)Promise且值是一個(gè)數(shù)組,數(shù)組之中有兩個(gè)元素,如果索引為0的元素不為空值,說明該請求報(bào)錯(cuò),如果索引0的元素為空值說明該請求沒有報(bào)錯(cuò),也就是成功。

使用很簡單

我們該怎么去使用這個(gè)to函數(shù)呢?其實(shí)很簡單,還是剛剛的例子

const handleLogin = async () => {
const [resErr, res] = await to(request('/basic/login', {
usename: 'sunshine',
password: '123456'
}))
if (resErr) {
// fail do somthing
return
}
const [userErr, info] = await to(request('/basic/getuserinfo', {
id: res.id
}))
if (userErr) {
// fail do somthing
return
}
this.userInfo = info
}

所以說,偶爾看看一些庫的源碼,還是能學(xué)到東西的!!!


當(dāng)前題目:Async/Await你是會(huì)用,但是你知道怎么處理錯(cuò)誤嗎?
URL標(biāo)題:http://uogjgqi.cn/article/dpshggp.html
掃二維碼與項(xiàng)目經(jīng)理溝通

我們在微信上24小時(shí)期待你的聲音

解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流