Asynchronous operations take up most of the time in everyday business coding, and this article presents an elegant approach to asynchronous operations. Make promises no longer try-catch, making asynchronous programming branches smoother and the development experience better. It also forces the developer to put the exception first in order to avoid forgetting try-catch and causing a bunch of Unhandled Promise Rejection.
/** * Promise eliminates the need for try catch, making asynchronous programming branches smoother and the development experience better. It also forces the developer to put the exception first in order to avoid forgetting the try catch and getting a bunch of Unhandled Promise rejection * *@param promise
* @returns Return tuple, error on failure, null on success, and return value on second. * /
export async function box<T> (
promise: Promise<T>,
) :Promise"[Err: (Error & T) | null.Res: T | null] >{
try {
return [null.await promise];
} catch (error) {
return [error, null]; }}Copy the code
Version 1
try {
const resp = await fetchList();
// do a lot of processing with resp
// do a lot of processing with resp
// do a lot of processing with resp
// do a lot of processing with resp
} catch (error) {
// Processing error
logger.error(error);
}
Copy the code
Version 1 violated “try-catch for large chunks of code, preventing the program from responding correctly to different exceptions and preventing it from locating the problem”.
Version 2
Try-catch only for requests.
let resp: IListResp; The declaration type needs to be displayed, otherwise the type will be any
try {
resp = await fetchList();
} catch (error) {
// Processing error
logger.error(error);
return; // Exit immediately after handling the error
}
// do a lot of processing with resp
// do a lot of processing with resp
// do a lot of processing with resp
// do a lot of processing with resp
Copy the code
Version 2 has a flaw: the declaration type needs to be displayed, otherwise the return value type will be any.
Version 3
const [error, resp] = await box(fetchList()); // Error and RESP automatically infer the type
if (error) {
// Processing error
logger.error(error);
return;
}
// do a lot of processing with resp
// do a lot of processing with resp
// do a lot of processing with resp
// do a lot of processing with resp
Copy the code
Version 3 puts errors first, making error handling impossible to forget and more natural, similar to go.