Skip to content

JS 实现类似 go 语法处理 async 错误 #34

Description

@roojay

通过 to 函数对 async 函数的返回进行一层包裹处理

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

// test.js
import to from './to.js';
async function asyncTask() {
  const [err, res] = await to(ajaxGetData());
  if(err) console.error('请求服务错误!');
}

原文链接: How to write async await without try-catch blocks in Javascript

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions