您的位置:首页 > 汽车 > 时评 > 开发工具推荐:await-to-js

开发工具推荐:await-to-js

2024/9/8 8:54:10 来源:https://blog.csdn.net/qq_42543244/article/details/140591525  浏览:    关键词:开发工具推荐:await-to-js

目录

前言:

1. .then().catch() 

2. async + await

3. await-to-js


前言:

        今天给大家推荐一块我觉得用着还不错的工具,await-to-js;

await-to-js - npm   GitHub - scopsy/await-to-js: Async await wrapper for easy error handling without try-catch

借用官网的一句话:Async await wrapper for easy error handling,方便让我们去处理错误,降低我们的编写成本;

安装:

npm i await-to-js --save

 引用:

import to from 'await-to-js';

ok,我们先来写一个假装一步请求的方法:

function httpGetList(status) {return new Promise((reslove, reject) => {if (status === 200) {reslove({ code: 200, data: [], msg: '操作成功' });} else if (status === 500) {reject(new Error('http 请求错误'));}});
}

在我们不使用此工具之前,看我们的调用方式,假设我们的请求发生了错误哈

1. .then().catch() 

下面这么写是ok的

httpGetList(500).then((resp) => {console.log(resp);
}).catch((err) => {});

但是当我们懒省事 不写.catch()时;

httpGetList(500).then((resp) => {console.log(resp);
});

2. async + await

下面这种因为没有错误捕获,所以也会报错。

async getListSuccess() {const resp = await httpGetList(500);console.log(resp);
}

 结合try catch,这种倒是ok,成功捕获了错误,但是又多了几行代码

try {const resp = await httpGetList(500);console.log(resp);
} catch (error) {console.log(error);
}

有意思的写法:async + await + catch,主打一个随心所欲

const resp = await httpGetList(500).catch((err) => {console.log(err);
});
console.log(resp);

ok,如今我们有了await-to-js,看看会发生什么变化?

3.await-to-js

const [err, resp] = await to(httpGetList(500));
console.log('err===>', err);
console.log('resp===>', resp);

我们就拿到了捕获的异常err,以及resp,下面就是你想怎么判断就怎么判断。

比我请求,只看code是不是200请求成功,其他的一概不管。我就可以这样写;

async getListSuccess() {const [err, resp] = await to(httpGetList(200));if (resp?.code === 200) {console.log(resp.data);this.list = resp.data;}console.log('继续执行吧');
}

 

 除此之外,还支持TypeScript的写法,快去探索吧!结束!

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com