foreword
In daily development, I believe that everyone will use asynchronous functions more or less, so how should asynchronous functions catch errors gracefully? If you try catch
know let's learn the usage and source code of await-to-js together ! The source code plus comments are only 22 lines!
harvest list
- Catching await errors gracefully
- Debug source code
await-to-js application
Introduction
The official introduction is as follows, to the effect that the asynchronous wait wrapper facilitates error handling
use
The old rules, see the readme for the usage method . At this time, some people may say, I use it try catch
well, why do I need to introduce a library to catch errors, and what is the reason for choosing it? As the saying goes, there is no harm without comparison, let's compare the use of the two
try-catch to catch errors
const getData = async ()=>{
try {
const data1 = await fn1()
} catch (error) {
console.log(error)
}
try {
const data2 = await fn2()
} catch (error) {
console.log(error)
}
try {
const data3 = await fn3()
} catch (error) {
console.log(error)
}
}
复制代码
await-to-js catches errors
import to from 'await-to-js';
const awaitGetData = async()=>{
const [err1,data1] = to(Promise)
if(err1) throw new (error);
const [err2,data2] = to(Promise)
if(err2) throw new (error);
const [err3,data3] = to(Promise)
if(err3) throw new (error);
}
复制代码
By comparison, we can know that await-to-js will directly return the error, and the code is more concise
code preparation
download code
git clone https://github.com/scopsy/await-to-js.git
cd await-to-js
npm install
复制代码
code analysis
debug code
The function of enabling debugging is to follow the author's thinking in single-step debugging. The test command here runs test cases, and you can set a test.ts
breakpoint on the function in advance (as shown in Figure 2)~
Find source code analysis
/**
* @param { Promise } promise
* @param { Object= } errorExt - Additional Information you can pass to the err object
* @return { Promise }
*/
// 参数promise处理函数,类型为promise的泛型;errorExt为返回错误的附加参数,选传、类型为对象
export function to<T, U = Error> (
promise: Promise<T>,
errorExt?: object
// 返回值为捕获的错误error或者处理成功后的data
): Promise<[U, undefined] | [null, T]> {
return promise
.then<[null, T]>((data: T) => [null, data])
.catch<[U, undefined]>((err: U) => {
// 若有附加参数,利用Object.assign将其跟捕获的错误复制到同一个对象中
if (errorExt) {
const parsedError = Object.assign({}, err, errorExt);
return [parsedError, undefined];
}
return [err, undefined];
});
}
export default to;
复制代码