Basic understanding and use of async and await

The meaning and usage of async function

	异步操作是JavaScript编程的麻烦事,一直有人提出各种各样的方案,试图解决这个问题!
	从最早的回调函数,到Priomise对象,到Generator函数,每次都有所改进但是都不彻底!
	async函数很多人人为它就是异步操作的终极解决方案。
async函数:
	1:函数的返回值为promise对象
	2:promise对象的结果由async函数执行的返回值决定

Usage of async function:

	1:同Generator函数一样,async函数返回一个promise对象,可以使用then方法添加回调函数。
	2:当函数执行的时候,一旦遇到await就会先返回,等到触发的异步操作完成,再接着执行函数体后面的语句。
  <script>
    async function test() {
    
    
      //  1:如果返回值是一个非promise类型的数据,该promise的状态就是fufilled
      return 5211314;
      
      // 2:如果是一个promise对象
      // return new Promise((resolve, reject) => {
    
    
      //   resolve('OK');
      //   reject('Error');
      // })

      // 3 抛出异常
      // throw 'oh No!!'
    }
    	let result = test();
    	console.log(result);
  </script>

The corresponding code status is as follows:
Insert picture description here
Insert picture description here
Insert picture description here

The meaning and usage of await function

说白了,await就是对promise成功的对象做一个获取,失败就try...catch
1:await右侧的表达式一般为promise对象,但也可以是其他的值
2:如果表达式是promise对象,await返回的是promise成功的值
3:如果表达式是其他值,直接将此值作为await的返回值。
注意:
1:await必须写在async函数中,但是async函数中可以没有await
2:如果await的promise失败了,就会抛出异常,需要通过try...catch捕获

The example code is as follows:

  <script>
    async function main() {
    
    
      let p = new Promise((resolve, reject) => {
    
    
        resolve('OK');
      })
      //  await右侧为promise的情况,所以会返回上述resolve('ok')的值
      let result = await p;
      console.log(result);
    }
    // 执行函数
    main();
  </script>

Insert picture description here
Case 2: This situation is rare, generally the right side is a promise object

  <script>
    async function main() {
    
    
      let p = new Promise((resolve, reject) => {
    
    
        resolve('OK');
      })
      //  1.await右侧为promise的情况,所以会返回上述resolve('ok')的值
      let result = await p;
      // 2.await右侧为其他类型的数据, 是啥就返回啥 
      let result1=await 521;
      console.log(result1);
    }
    // 执行函数
    main();
  </script>

Insert picture description here
Case 3: The right side of await is the failed promise state
Insert picture description here

  <script>
    async function main() {
    
    
      let p = new Promise((resolve, reject) => {
    
    
        // resolve('OK');
        reject('Error');
      })

      try {
    
    
        let result3 = await p;
      }catch(error){
    
    
        console.log(error);
      }
    }
    // 执行函数
    main();
  </script>

Example result: output print this exception! Get this result in catch.
Insert picture description here

The combination of async and await, small case and pure callback for comparison

Use the combination of await and async to read the contents of three html files and make a splicing! !

  <script>
    // async和await的结合方法实现
    async function main(){
    
    
      try{
    
    
        // 目标读取三个html文件中得内容,然后进行一个拼接!
        // 读取第一个文件的内容
        let data1= await mineReadFile('./resource/ajia1.html');
        let data2= await mineReadFile('./resource/ajia1.html2');
        let data3= await mineReadFile('./resource/ajia1.html3');
        console.log(data1+data2+data3);
      }catch(e){
    
    
        console.log(e);
        }
    }

    main();
  </script>

Use pure callback function to realize, read the content in three html files, make a splicing! !

    // 回调函数的方式
    const fs=require('fs');
    fs.readFile('./resource/ajia1.html',(err,data1)=>{
    
    
      if(err) throw err;
      fs.readFile('./resource/ajia1.html',(err,data2)=>{
    
    
        if(err) throw err;
        fs.readFile('./resource/ajia1.html',(err,data3)=>{
    
    
          if(err) throw err;
          console.log(data1+data2+data3);
            })
        })
    })

As you can see, the two want to compare:

1:在错误处理这方面,async和await结合方式,用try catch包裹就可以,比原来使用纯回调函数要方便的多!不需要一层层判断。
2:在async和await的使用过程中,我们是看不到回调函数的!
3:在promise的then方法和catch方法中,可以看到有回调函数。
4:非常简洁,就类似于我们写同步函数调用的方式,只不过在前面多了个await,但是他的内部的执行确是异步的。

It can be seen that the combination of async and await is very concise, similar to the way we write synchronous function calls, except that there is an await in front, but its internal execution is indeed asynchronous.

Guess you like

Origin blog.csdn.net/czj1049561601/article/details/114238733