Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the js async function

Shulou Source: shulou.com Published: 2022-06-02 15:52:48 10月31日 Update

This article focuses on "how to use the js async function", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the js async function.

The async function is the syntax sugar of the Generator function. The async function simply replaces the asterisk (*) of the Generator function with async and yield with await, that's all.

The improvement point of async function to Generator function

The built-in executor does not need to call next () like the Generator function to make the function execute.

Better semantics

The promise object is returned

The async function returns a promise object

The async function returns a Promise object. The value returned by the return statement inside the async function becomes the parameter of the callback function of the then method. An error is thrown inside the async function, which causes the returned Promise object to become reject. The error object thrown will be received by the callback function of the catch method

See the following example:

LettestAsync=asyncfunction () {

/ / thrownewError ('throw an error ~')

Reject ()

}

TestAsync () .then (resolve= > {

Console.log (`resolve:$ {resolve} `)

}, reject= > {

Console.log (`reject:$ {reject} `); / / the callback function in which the status changes to reject will be executed. If there is no callback function here, catch will capture it. This is the thing of promise.

}) .catch (err= > {

Console.log (`err:$ {err} `)

})

If any Promise object following an await statement changes to the reject state, the entire async function interrupts execution.

Asyncfunctionf () {

AwaitPromise.reject ('error')

AwaitPromise.resolve ('helloworld'); / / will not be executed

}

/ / the promise statement on the second line will not be executed

At this point, I believe you have a deeper understanding of "how to use the js async function". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Functions objects methods states statements errors content that is learning practical deeper that's all things examples interests parameters practicality practicality simple operation asterisks Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MySQL Shulou Information NVidia macOS