美文网首页
js中Async/Await 怎么做错误处理更好?

js中Async/Await 怎么做错误处理更好?

作者: Small_Song | 来源:发表于2021-09-18 09:31 被阅读0次

await等待处理的是一个Promise协议,那么利用以下这种方式将错误导出至同一个逻辑层再处理就能不用写那么多try/catch了。

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

import to from './to.js';
async function asyncTask(cb) {  
     let err, user, savedTask;

     [err, user] = await to(UserModel.findById(1));
     if(!user) return cb('No user found');

     [err, savedTask] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
     if(err) return cb('Error occurred while saving task');

    if(user.notificationsEnabled) {
       const [err] = await to(NotificationService.sendNotification(user.id, 'Task Created'));  
       if(err) return cb('Error while sending notification');
    }

    cb(null, savedTask);
}

另外async await需要注意以下:

async function x() {
      await y();
}
async function y() {
      await x();
}
x() //Uncaught (in promise) RangeError: Maximum call stack size exceeded

相关文章

  • js中Async/Await 怎么做错误处理更好?

    await等待处理的是一个Promise协议,那么利用以下这种方式将错误导出至同一个逻辑层再处理就能不用写那么多t...

  • 从零开始的Koa实战(1) 初识Koa

    前期准备 为了更好的使用 async/await ,我们选择 7.6.0 以上的 node.js 环境,当然,我们...

  • es6--async和await

    async 和 await被称为js异步的最终解决方案,那么我们来了解下:async:异步方法, await:等待...

  • 小程序 async await的使用

    在要使用async await的文件中,引入这个regeneratorRuntime.js promisify.j...

  • js异步编程(updating)

    js 异步编程方式: Promise,generator/yield,async/await 回掉函数 js事件监...

  • async和await

    浅谈Async/Await用 async/await 来处理异步 async和await async:声明一个异步...

  • 目录

    JS篇 Promise Iterator Generator async-await[https://www.ji...

  • 2019-03-06

    1.行文思路 JS中处理异步 由callback->promise->generater->async/await...

  • JS 中的 async/await

    async/await 是什么? async/await 是 ES2017 中新增的异步解决方案; await 只...

  • Koa基础 Async/Await 函数

    Async/Await 函数的特点 更好的语义,相比较Generator 对象的yield, Async/Awai...

网友评论

      本文标题:js中Async/Await 怎么做错误处理更好?

      本文链接:https://www.haomeiwen.com/subject/sphsgltx.html