Handle async/await errors gracefully

async/await usage

async/await solves the callback hell caused by Promise's chain calls (.then), making asynchronous callbacks as beautiful as synchronization!

is used as follows:
Insert image description here
It can be seen that in the syncFun function, we obtain asynchronous information, and the writing method is the same as synchronous, without using .then to set .then, which is very beautiful!

What will happen if the error is not captured
Insert image description here
Console:
Insert image description here
It can be seen that the console does not have the information we want to print console.log('s1 , s2 have been obtained, I will execute it')

try/catch captures errors
In our daily development, try/catch is used to capture errors as follows:
Insert image description here
Console: a>
Insert image description here

It can be seen that we threw two rejects, but only caught one error!
Then to catch multiple errors, we need multiple try/catch, so the code looks like this:
Insert image description here
Console:
Insert image description here
Just two try/catch already seems uncomfortable, but what about 10?

await-to-js
Insert image description here
The await command is followed by a Promise object, and the result of the object is returned. If it is not a Promise object, the corresponding value is returned directly
A to function is encapsulated here, which receives promise and extended error information as parameters and returns promise. [err, res] represents the error message and successful result respectively. When .then() succeeds, [null, res] represents the error message is null; when .catch() fails, [err, undefined] represents the successful result is undefined. We can get the captured results directly from the returned array. The first one is the failure information, and the second one is the success result!

Complete code plus use
Insert image description here
Learn this and show it off in front of the interviewer. The interviewer will definitely call you elegant! ! !

Guess you like

Origin blog.csdn.net/longxiaobao123/article/details/134050380