Created
March 23, 2021 03:36
-
-
Save suyanhanx/8c1f45f806229bd94a398a8b75cc2153 to your computer and use it in GitHub Desktop.
ts 中 处理错误
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 获取 promise 的 tuple | |
* | |
* @export | |
* @template T | |
* @template R | |
* @param promise 需要获取结果的 promise 对象 | |
* @returns {(Promise<[R] | [null, T]>)} | |
*/ | |
export async function getAsyncTuple<T = any, R = Error>(promise: Promise<T>): Promise<[R] | [null, T]> { | |
try { | |
const result = await promise | |
return [null, result] | |
} catch (e) { | |
return [e] | |
} | |
} | |
/** | |
* 使用方法 | |
*/ | |
const [err, result] = await getAsyncTuple(fetchXXX); | |
if(err){ | |
return; | |
} | |
console.log(result); | |
// 如果try catch涉及逻辑,一般这么包一层。否则就直接用个大的 try catch 全都包了,,, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment