Async/await decorater for easy error handling in js, inspired by await-to-js
You development need support use async/await functionality. You can decorate your class property functions with decorator, if you use babel to support class properties
- Fully compatible with
await-to-js
- No
try catch
statement, auto catch error - Very simple to use, support decorate class properties function
- Don't
import to from 'await-to-js'
everywhere, just inapi service
file
npm i --save await-to-decorater
# use yarn
yarn add await-to-decorater
// you can import to
from await-to-decorater
to use
// always import `to` to wrap
import { to } from "await-to-decorater";
import { getTigers } from "./api";
loadData = async () => {
const [err, res] = await to(getTigers());
// ...
};
// api.js --- your api service file
import Catch from "await-to-decorater";
import axios from "axios";
// Simply declare a service class to make your code structure clearer
class ZooService {
@Catch()
getAnimal() {
return axios.get("xxx/animals");
}
// class properties and with query
@Catch()
getTigers = type => {
return axios.get(`xxx/tigers/${type}`);
};
// error extra
@Catch({ extra: "example" })
getLions = () => {
return axios.get("xxx/tigers");
};
}
// export instance
export default new ZooService();
// app.js -- your app or components file etc
import api from "./xxx/ZooService";
loadAnimals = async () => {
//auto catch your async function error, no try catch
const [err, res] = await api.getAnimal();
if (err) {
// error
} else {
//
}
};
loadTigers = async () => {
// pass query
const [err, res] = await api.getTigers("siberian");
// ...
};
loadLions = async () => {
const [err, res] = await api.getLions();
if (err) {
// err.extra === 'example' same to await-to-js extra
}
};
These are stage-0 decorators because while the decorators spec has changed and is now stage-2, which is very incompatible with stage-2. But the js compiler is not yet supported the new decorater proposal,seems to take a long time, so it's safely to use in your project
MIT © duziten