async/await

什么是async/await

async/await是ES8引入的新语法,用来简化Promise异步操作。在async/await出现之前,开发者只能通过链式.then()的方式处理Promise异步操作。

.then链式调用的优点:

      解决了回调地狱的问题;

.then链式调用的缺点:

       代码冗余、阅读性差、不易理解

async/await的基本使用

      使用async/await简化Promise异步操作:

import thenFs from 'then-fs'

// 按照顺序读取文件1,2,3的内容
async function getAllFile() {
    const r1 = await thenFs.readFile('../text/1.txt', 'utf8');
    console.log('r1:', r1);
    const r2 = await thenFs.readFile('../text/2.txt', 'utf8');
    console.log('r2:', r2);
    const r3 = await thenFs.readFile('../text/3.txt', 'utf8');
    console.log('r3:', r3);
}
getAllFile()

 不需要.then就可以直接拿到最终的结果: 

 

 

async/await 的使用注意事项:

  1. 如果function中使用了await,则function必须被async修饰;
  2. 在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行

 

posted @ 2022-05-24 19:12  perfect*  阅读(23)  评论(0编辑  收藏  举报
$(function() { $('#cnblogs_post_body img').each(function() { let imgSrc = $(this).attr('src'); let year = parseInt(imgSrc.substr(imgSrc.indexOf('g')+1,4)); if(year >= 2022){ imgSrc += `?watermark/2/text/amlndWl5YW4=/font/5a6L5L2T/fontsize/15/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast`; $(this).attr('src', imgSrc) } }) })