catching
Catch promise reject, return as promise resolve.Often used in async function, together with await.
Install
npm install catching
Use
import catching from 'catching'
async doOperation() {
const ret = await catching(yourPromiseFn())
// Here you need differ resolve and reject by: code or instanceof Error, etc.
const isOK = ...
if (!isOK) {
throw ret
}
else {
// ... next step
}
}
Why
Normally when we use async/await, we would use try-catch for promise reject scenario.But the code written by try-catch is not concise, while it indeed differentiates abnormal case from normal.
Code looks like below,
addUserDAO
reject promise while meeting error.async addUserService() {
try {
const ret = await addUserDAO()
}
catch (err) {
throw err
}
}
function addUserDAO () {
return new Promise((res, rej) => {
// const isOK = ...
if (OK) {
res({ data })
}
else {
rej({ data, code })
}
})
}
How
import catching from 'catching'
async addUserService() {
const ret = await catching(addUserDAO())
if (!ret.code) {
throw ret
}
else {
// ... next step
}
}