尝试TM
别让恐怖的捕捉塔毁了你那漂亮的一行人.
使用量
npm install @bdsqqq/try
import { trytm } from "@bdsqqq/try";
const mockPromise = () => {
return new Promise<string>((resolve, _) => {
setTimeout(() => {
resolve("hello from promise");
}, 1000);
});
};
const mockPromiseThatFails = () => {
return new Promise<string>((_, reject) => {
setTimeout(() => {
reject(new Error("hello from promise"));
}, 1000);
});
};
const [data, error] = await trytm(mockPromise());
const [data2, error2] = await trytm(mockPromiseThatFails());
这为什么存在?
Async 等待感觉像天堂,因为它避免了回叫地狱或"末日"(Pyramid of Doom),用行格式写出同声编码:
function hell() {
step1((a) => {
step2((b) => {
step3((c) => {
// ...
})
})
})
}
async function heaven(){
const a = await step1();
const b = await step2(a);
const c = await step3(b);
// ...
}
在错误处理开始之前... 因为那时你终于有了恐怖的Try-Catch塔 在那里你美丽的单行体神奇地扩张到至少5行代码:
async function Terror(){
let a;
let b;
let c;
try {
a = await step1();
} catch (error) {
handle(error);
}
try {
b = await step2(a);
} catch (error) {
handle(error);
}
try {
c = await step3(b);
} catch (error) {
handle(error);
}
// ...
}
一个简单的解决方案是 附加 .catch() 每个承诺的结尾:
async function easy(){
const a = await step1().catch(err => handle(err));
const b = await step2(a).catch(err => handle(err));
const c = await step3(b).catch(err => handle(err));
// ...
}
这种方法解决了问题,但可以有一点重复性,另一种方法是创建一个功能,执行一个尝试Catch来取代其他所有:
import { trytm } from "@bdsqqq/try"
async function awesome() {
const [aData, aError] = await trytm(step1());
if(aError) // ...
const [bData, bError] = await trytm(step2(aData));
if(bError) // ...
const [cData, cError] = await trytm(step3(bData));
if(cError) // ...
// ...
}
为什么这真的存在?
我看着 一个火船短 最后在兔子洞里学习如何发布国家防范机制的套件. 这在您的代码库中仍然是个有趣的模式, 但最好粘贴副本而不是依赖.
我把源代码留在这儿 这样你就可以不用在 /src 文件夹中查找 .ts 文件了:
export const trytm = async <T>(
promise: Promise<T>,
): Promise<[T, null] | [null, Error]> => {
try {
const data = await promise;
return [data, null];
} catch (throwable) {
if (throwable instanceof Error) return [null, throwable];
throw throwable;
}
};
捐款
这个密码被公然盗取 一个火船youtube短,加上小的添加 data 从承诺中推断出这是个争论.