目录

前言:

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的写法,快去探索吧!结束!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐