async和await

async和await是解决异步编程问题的。

promise的then方法链式调用不够优雅

  1. async 修饰的函数同步返回一个promise
  2. 使用await必须包裹一个async修饰的函数
  3. async返回的promise的状态由await修饰的promise的状态决定
  4. 如果await修饰的promise未全部解决async返回的promise就是padding
  5. await修饰的promise是按书写顺序解决的(等上一个promise出来结果后这个promise才开始执行)
  6. 如果异步操作没有被await修饰则不影响返回的promise状态
const promisify = require('util').promisify
const readFile = promisify(require('fs').readFile)
const read = async function () {
  let r1 = await readFile('驿外.txt', 'utf-8')
  console.log(1);
  let r2 = await readFile('桃夭.txt', 'utf-8')
  console.log(2);
  let r3 = await readFile('孔雀东南飞.txt', 'utf-8')
  console.log(3);
  console.log(r1 + r2 + r3);

  const timeOut = new Promise((suc, err) => {
    setTimeout(() => {
      suc('到时间了')
    }, 2000)
  })
  let r4 = await timeOut
  console.log(r4);
  //等r4解决了才会输出
  console.log(r1);

  const timeOut2 = new Promise((suc, err) => {
   setTimeout(() => {
      //这个promise会老老实实的等上一个解决了才会开始解决
     console.log('xxxxxx');
     suc('我是第二个定时器')
   }, 1000)
  })
  let r5 = await timeOut2
  console.log(r5);

  return 'async函数里的await(等待的)promise全部完成!'
}
console.log(read().then(value => { console.log(value); }));
posted @ 2021-05-18 16:13  丁同亚的博客  阅读(65)  评论(0编辑  收藏  举报