Projects in vue3 use async/await with promise

passed in the project

Async:
[The async_function declaration is used to define an asynchronous function that returns an AsyncFunction object. An asynchronous function refers to a function that is executed asynchronously through the event loop, and it returns its result through an implicit Promise.
insert image description here

async/await
async/await is based on Promise and is a further optimization. However, when writing code, the API of Promise itself rarely appears, which is very close to the writing method of synchronous code.

async just indicates that there may be an asynchronous process in it, and there can be an await keyword in it. If there is no async function itself, it will return immediately without blocking the current thread. The return value of its function is a Promise object.

When return new Promise(); the promise object is processed directly

When return data; is equivalent to Promise.resolve(data); or a Promise object

Both need to be handled with the .then(data => { }) function.

The await is the resolve(data) message, and the data data is returned. For example, in the following code, when the Promise object changes from Pending to Resolved, the variable a is equal to data; then execute the following statements `console.log(a);

const a = await new Promise((resolve, reject) => {
    // async process ...
    return resolve(data);
});
console.log(a);

async/await
async is placed in front of the function as a keyword, indicating that the function is an asynchronous function, which means that the execution of the function will not block the execution of the following code.

The async function returns a Promise object (if a direct quantity is returned in the function, async will encapsulate the direct quantity into a Promise object through Promise.resolve()), so if the async function is executed without await, it will be executed immediately, And it will never block the following statement, which is no different from a normal function returning a Promise object.
insert image description here

The use cases of vue3 in actual projects are as follows:

//引入api
import { commonMethods } from "@/api/customer/new";
//_f封装方法 调用api接口
const   _f=()=>{
      return new Promise(resolve=>{
        commonMethods().then(res=>{
         const code = res.code
         const data = res.lists
          if(code === 200){
              resolve(data)
            }
        })
     })
 }; 
const actionPage = async () => {
     let data=await _f();
     console.log(data,'拿到同步的数据做操作')
};
actionPage();//初始加载

insert image description here
record it!!!

Guess you like

Origin blog.csdn.net/weixin_46409887/article/details/128904825
Recommended