解决代码中重复的捕获 promise 错误的 try catch 语句
promise
promise 的出現(xiàn),提供了優(yōu)雅的異步解決方式,但是,多個(gè)連續(xù)繼發(fā) promise 寫法依然繁瑣。
let promise = new Promise(function(resolve, reject){// ...if(/* 異步任務(wù)執(zhí)行成功 */) {resolve(value)} else {reject(error)} })promise.then(v => {}).catch(e => {}) 復(fù)制代碼async
es6 之后又新增了 async 函數(shù)來優(yōu)化異步寫法,語義化更明確,寫法更優(yōu)雅,但是錯(cuò)誤捕獲比較麻煩,一般都得使用 try catch 來捕獲錯(cuò)誤,具體優(yōu)點(diǎn)參考阮老師博客 async 函數(shù)
function promiseFunc = function(){return new Promise(function(resolve, reject){// ...if(/* 異步任務(wù)執(zhí)行成功 */) {resolve(value)} else {reject(error)}}) }async func(){let res = await promiseFunc() }// 錯(cuò)誤捕獲 async func(){try{let res = await promiseFunc()}catch(err){alert(err)} }復(fù)制代碼錯(cuò)誤捕獲優(yōu)化
如下是工作中 react + mobx 項(xiàng)目中 action 的代碼
class Actions {@actionasync deleteModel(params) {try {await this.post(apis.API_DEPLOY_DELETE, params)this.getDeployList(this.store.searchParams)} catch (e) {message.error(e.message || '出錯(cuò)了!請(qǐng)稍后重試')}}@actionasync getDirChain(params) {try {let r = await this.post(apis.API_DEPLOY_DIR_CHAIN, params)runInAction(() => {this.store.dirChain = r})} catch (e) {message.error(e.message || '出錯(cuò)了!請(qǐng)稍后重試')}}} 復(fù)制代碼如上代碼,兩個(gè) action 都是向后端異步請(qǐng)求數(shù)據(jù), 每個(gè) action 函數(shù)中都用了 try catch 函數(shù),這樣重復(fù)寫了幾十個(gè) action 函數(shù)
必須干掉 try catch
錯(cuò)誤捕獲裝飾器嘗試
裝飾器簡(jiǎn)潔方便,首先嘗試, class 方法裝飾器函數(shù)如下
const tryCatch = msg => (target, name, descriptor) => {const original = descriptor.valueif (typeof original === 'function') {descriptor.value = async function(...args) {try {const result = await original.apply(this, args)return result} catch (e) {message.error(e.message || msg || '出錯(cuò)了!請(qǐng)稍后重試')}}}return descriptor } 復(fù)制代碼如上代碼,封裝 tryCatch 裝飾器來對(duì)每個(gè) action 函數(shù)添加 try catch 錯(cuò)誤捕獲。
屬性方法裝飾器中
- target 指向 class 實(shí)例
- name 是被裝飾的方法名
- descriptor 是方法的屬性修飾符
我們可以通過 descriptor.value 獲取到被裝飾的方法,在 try catch 中執(zhí)行函數(shù),捕獲錯(cuò)誤或者返回結(jié)果
為了靈活提示錯(cuò)誤信息,裝飾器參數(shù) msg 用來傳入自定義提示文本
- 用法(該用法是錯(cuò)誤的)
以上對(duì) async 函數(shù)進(jìn)行錯(cuò)誤捕獲的用法是錯(cuò)誤的
如上的寫法是錯(cuò)誤的,這種裝飾器只能對(duì)同步代碼產(chǎn)生作用,異步的是無效的,之前理解錯(cuò)誤了
最后還是解決了 try catch 問題
直接 async await 函數(shù)封裝就行了,簡(jiǎn)單的問題想復(fù)雜了。。。
定義請(qǐng)求執(zhí)行公共函數(shù)
/*** @param {string} method request method; ('get', 'post')* @param {string} api request url* @param {object} params payload* @memberof BaseActions*/ request = async (method, api, params = {}) => {const requestFunc = async () => {let r = nulltry {r = await this[method](api, params)} catch (e) {message.error(e.message)}return r}return await requestFunc() } 復(fù)制代碼原有包含 try catch 重復(fù)代碼函數(shù)修改
@action async getDirChain(params) {let r = await this.request('get', apis.API_DEPLOY_DIR_CHAIN, params)r && runInAction(() => this.store.dirChain = r) } 復(fù)制代碼終于不用不停寫重復(fù)代碼了。。。
總結(jié)
以上是生活随笔為你收集整理的解决代码中重复的捕获 promise 错误的 try catch 语句的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 覆盖网络 Flannel 0.7
- 下一篇: Smart Link