async await promise

async 异步函数,以后可能会用得很广。

1、箭头函数: 没有{ }时不写return 也有返回值

2、Promise : 异步神器,很多异步api都是基于Promise

3、new Promise().then().then().catch() :第一个then触发条件:是 Promise() 实例化时resolve()触发, 第二个及以后的then() 触发条件是前一个then() 执行完成,并且将return值作为下一个then的参数

4、async: 异步函数

5、await : 后面必须跟Promise对象,若非Promise,则不会拦截后面代码执行。当promise对象resolve过后并且执行完then里面的代码,就执行下一步代码,不resolve不会触发下一行代码执行。

需注意:如果then()中需要异步操作,不会等then中的异步执行完过后再执行下一个then()的函数。原因就是,异步函数中,没有地方给你return给then()回调函数。解决方案是async函数。

也就是说Promise对于异步的帮助 其实很有限,.then()只有第一个有用而已。

 1   const aa = _ => new Promise((res, rej) => { // 设置aa函数返回promise对象
 2         setTimeout(function() {
 3             console.log('1')
 4             res('2')
 5         }, 1000);
 6     })
 7   let bb = async function() {
 8       await aa().then((res) => { // await会等待aa()执行完,并且then代码也执行完,当然,then代码里面的异步操作不会执行。
 9         console.log(res)
10         setTimeout(function(){  
11             console.log('4') // then中的代码执行完直接进入下一个then,这个then 其实return了undifined
12             return 'sdf'
13         }, 2000)
14       }).then(res => {
15           console.log(res) // undifined
16       })
17       console.log('3')
18   }
19   console.log(bb()) // Promise {<pending>}
// console 结果 :
Promise { <pending> }
1
2
undifined
3
4

 目标:当A异步任务完成后,继续并发n个B异步任务,使用asnyc函数实现

这儿具体是读文件夹,读完后读文件夹中的所有文件。

const readdir = function (path) { // 读文件函数
  return new Promise((res, rej) => {
    fs.readdir(path, (err, files) => {
      if(err) res(err)
      res(files)
    })
  })
}
const stat = function (path) { // 确认是否是文件夹
  return new Promise((res, rej) => {
    fs.stat(path, (err, file) => {
      if(err) res(err)
      file.isDirectory() ? res('dir') :res('file') // 返回类型结果
    })
  })
}
const getdirs = async function(ctx) {
  let sendFiles = []
  const files = await readdir(filePath) // 读文件夹
  const promises = files.map(function(file){ // 利用map函数特性,返回值组成新的数组,这儿并没有用async函数,map内并不等待一个stat回来后再进行另一个stat,是同时进行的。
    return stat(filePath + '/' + file)
      .then(res => {
        if(res === 'dir') sendFiles.push(file)
      })
  })
  await Promise.all(promises) // 这儿是异步并发的关键,在这个位置等待所有promise对象resolve。
  ctx.body = sendFiles 
}

原文地址:https://www.cnblogs.com/gsgs/p/7074984.html