Promise 之 async & await

Interpretation of promise

When it comes to promises, it has to be synchronous and asynchronous. The execution environment of JS is single-threaded, which means that only one task can be completed at a time. If there are multiple tasks, blocking will occur, and the asynchronous mode can execute multiple tasks together , Common asynchronous calls such as: scheduled tasks, ajax, event functions.

  • Promise mainly solves the problem of asynchronous deep nesting, avoiding the problem of nested regions

  • Below we simply write a Demo to talk about basic usage

Basic API of promise

  • Through this list, we can see that the promise has three APIs, namely: .then, .catch, .finally

    • .then: get the correct result of the asynchronous task, which is the success above

    • .catch: get abnormal information, which is the above error

    • .finally: It will be executed anyway, generally used to release resources in java

  • The above two methods can be called directly by the class name, which is a static method

    • .all: This method accepts an array where the objects in the array are all Promise real columns, and relect is also an array, one by one corresponding to the response of each request, the callback is a jso string

    • .race: This method accepts an array where the objects in the array are all Promise real columns. When the status of one of the requests changes, you will get a response, and will not wait for the rest of the response.

async 和 await

  • async as a keyword in front of the function

    • Any asyncfunction will implicitly return apromise

  • awaitKeywords can only be used asyncin functions that use definitions

    • Await can be directly followed by a Promise instance object

    • The await function cannot be used alone

  • async / await makes asynchronous code look and behave more like synchronous code

  • When async handles multiple asynchronous functions, we add the await keyword, the current request will only execute the next sentence of code after returning

.

Guess you like

Origin www.cnblogs.com/msi-chen/p/12713414.html
Recommended