Usage of async/await

1. Definition of async and await

async 是异步的意思,而 await 是等待的意思,await 用于等待一个异步任务执行完成的结果。
1.async/await 是一种编写异步代码的新方法(以前是采用回调和 promise)。
2. async/await 是建立在 promise 的基础上。
3. async/await 像 promise 一样,也是非阻塞的。
4. async/await 让异步代码看起来、表现起来更像同步代码。

Usage scenarios
In actual development, if you encounter the problem of waiting for the first request to return data before executing the second request (maybe the parameters to be passed in the second request are the data returned by the first request interface).

code

const datas = async ()=> {
    
    
	  await request.selectPies(Route.path.split('/')[3]).then(res=>{
    
    
	  	states.ids = res.obj
	  })
	  //查询发帖子用户信息
	  await request.selectUsers(states.ids).then(res=>{
    
    
	    console.log(res.obj)
	  })
	}
	datas()

1. async

	async function testAsync(){
    
    		//带async关键字的函数,是声明异步函数,返回值是promise对象,
		return 'Hello async';
	}
	testAsync();					//打印结果:Promise {<fulfilled>: 'Hello async'}

2. Obtain data from asynchronous functions

method 1:

	async function testAsync(){
    
    		
		return 'Hello async';
	}
	var result = testAsync();
	result.then((data)=>{
    
    
	    console.log(data);			//Hello async
	})

Method 2:

function getData(){
    
    
		return 'Hello async';
	}
	async function test(){
    
    
		var d = await getData();	//await 是等待异步方法执行完成,可以获取异步方法里面的数据,但是必须得用在异步方法里面
	}
	test();							//Hello async

3. Application scenarios

First request interface 1. After getting the result returned by interface 1, use it as a parameter of interface 2, and then request interface 2.

	async function getD(){
    
    
		var a = await getDataF()	//接口1
		var b = await getDataS(a)	//接口2
		console.log(b);				//接口2返回的值
	}
	getD()

4. Precautions

1. async is used to declare that a function is asynchronous, while await is used to wait for the completion of an asynchronous method.
2. await can only be used in async functions, otherwise an error will be reported.
3. The async function returns a Promise object with a status of fuifilled.
4. Similar to queuing up to buy something, after one person has paid, it is the next person's turn. In the async function, await stipulates that asynchronous operations can only be queued up and executed one by one, so as to achieve the effect of executing asynchronous operations in a synchronous manner.

Guess you like

Origin blog.csdn.net/qq_52654932/article/details/130373910