Promise object

The Promise object is a new constructor in ES6 that solves the problem of callback hell.

Promise is a container for placing an asynchronous task

There are three states in a container:

Pending - Asynchronous task is being executed Rejected - Asynchronous task is completed Resolved - Asynchronous task is successfully executedCopy the code

Only promise instances have then methods, which solve callback hell by getting the return value of the previous callback function

Async function

Async functions are also new to ES6. This, in combination with Promise, causes asynchronous code to execute as synchronous code, with no callbacks

The return value of async function

The return value inside async function

If the return Promise object is returned, it is returned directly

If return is not a Promise object, wrap it as a Promise and return

So async returns a Promise object no matter what

So how do we get the results?

(1).then gets the result (2) in another async function with awaitCopy the code
<script> async function main() {// Async will wrap the non-promise object of return into an immediate Resolve Promise object return 123 // async will wrap the return into a Promise object Return new Promise(function (resolve, Reject) {resolve(123)})} const ret = main() then(data => {console.log(data)}) // Async function f() {const ret = await main() console.log(ret); } f() </script>Copy the code

await

Await can only be used in async functions, which assigns the result of the following expression to the preceding member

application

These three additions to ES6 are often used when AXIos makes requests.

All axios requests support promises, are internally wrapped, and all support.then to get results.

When we use the await keyword followed by a promise instance object in an async function, await will wait for the result of a later asynchronous operation and then assign the value to the previous member.

Async handeShowlEditUser(item) {// Mark async function this.editdialogForm = true; Const res = await this.$HTTP ({// use await to receive axios request return value url: '/users/${item.id} ', method: 'get', // headers: { // Authorization: Window. The localStorage. The getItem (' token ') / /}}) if (res) data. The meta. Status = = = 200) {/ / direct access to the results, do not need to. Then method, Avoid the callback this.editUserForm = res.data.data}}Copy the code
Which functions can be marked async?
Any function, anonymous function, named function, arrow function, object property functionCopy the code