Skip to content

Instantly share code, notes, and snippets.

@suyanhanx
Created March 23, 2021 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suyanhanx/8c1f45f806229bd94a398a8b75cc2153 to your computer and use it in GitHub Desktop.
Save suyanhanx/8c1f45f806229bd94a398a8b75cc2153 to your computer and use it in GitHub Desktop.
ts 中 处理错误
/**
* 获取 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