to函数 对try catch 的函数包装,解决地狱嵌套,使函数扁平化,函数单一化原则

to函数 对try catch 的函数包装,解决地狱嵌套,使函数扁平化,函数单一化原则

// utils/promise.js
export function to(promise) {
  return promise
  .then(data => [null,data])
  .catch(err =>[err, undefined]);
}

import { fetchUserById } from './api';
import { to }from'./utils/promise';
async function displayUser(userId) {
  const [error,user] = await to(fetchUserById(userId));

  if (error || !user) {
    console.error('获取用户失败:,error);
    //..相应的错误处理逻辑
    return;
  }    
  // 到这里,代码的”快乐路径"是清晰且扁平的
  console.log('用户信息:,user.name);
  // ... 更多基于 user 的操作

ref
别再手动 try...catch 了:一种更优雅的 async/await 错误处理模式
https://mp.weixin.qq.com/s/iBK0AUavQeRzOvKBbm7uCw

posted @ 2025-06-24 09:46  彭成刚  阅读(32)  评论(0)    收藏  举报