laitimes

Gain an in-depth understanding of await and async

async

Placed before a function as a keyword, it means that the function is an asynchronous function, meaning that the execution of the function does not block the execution of the code that follows The call to the asynchronous function is the same as that of a normal function

It can be seen whether the order of execution or the function executes first, but the return result of the function is a Promise object, and the return value of the Promise should be obtained using the then method

At this point, the first output is the following string of text, indicating that the execution of the asynchronous function does not block the subsequent code execution, async's internal implementation principle is that if the function has a return value, when the function is called, the default will be called internally to convert it into a Promise object as a return, if the function throws an error inside, then call Promise.reject() to return a Promise object

Since async returns a Promise object, he can use all uses of The Promise, such as Promise.catch exceptions

await

await, or wait, is used to wait for a Promise object. It can only be used in the asynchronous function async function, otherwise an error is reported

Its return value is not the Result object but the Result of processing the Promise object

The await expression pauses the execution of the current async function and waits for The Promise processing to complete. If promise is fulfilled, the resolve function argument of its callback continues as the value of the await expression, and if promise handles the exception rejected, the await expression will throw the reason for the promise's exception. If the value of the expression after the await operator is not a Promise, the value is converted to a Promise that has been processed normally.

Contrast with Promise

1, no longer need multi-layer .then method

Suppose a business is completed in many steps, and each step is asynchronous, depending on the outcome of the previous step.

Gain an in-depth understanding of await and async

2. The Promise can be processed in parallel

Gain an in-depth understanding of await and async

Author: There is no weeder who is worried

Link: https://www.jianshu.com/p/fb1da22f335d

Source: Jian Shu

Copyright belongs to the author. For commercial reproduction, please contact the author for authorization, and for non-commercial reproduction, please indicate the source.