每天3分钟,重学ES6-ES12(十四)async/await-灵析社区

养乐多一瓶

前言

今天开始和大家一起系统的学习ES6+,每天3分钟,用一把斗地主的时间,重学ES6+,前面我们介绍了迭代器和生成器,今天继续介绍async 和 await

异步函数 async function

  • async关键字用于声明一个异步函数: async是asynchronous单词的缩写,异步、非同步; sync是synchronous单词的缩写,同步、同时;

异步函数的执行流程

  • 异步函数的内部代码执行过程和普通的函数是一致的,默认情况下也是会被同步执行。
  • 异步函数有返回值时,和普通函数会有区别: 情况一:异步函数也可以有返回值,但是异步函数的返回值会被包裹到Promise.resolve中; 情况二:如果我们的异步函数的返回值是Promise,Promise.resolve的状态会由Promise决定; 情况三:如果我们的异步函数的返回值是一个对象并且实现了thenable,那么会由对象的then方法来决定;
  • 如果我们在async中抛出了异常,那么程序它并不会像普通函数一样报错,而是会作为Promise的reject来传递;

异步函数和普通函数的区别-返回值

异步函数的返回值一定是一个Promise

async function foo() {
  console.log("中间代码~")

  // 1.返回一个值
  // promise then function exec:  1
  return 1

  // 2.返回thenable
  // promise then function exec:  hahahah
  return {
     then: function(resolve, reject) {
       resolve("hahahah")
     }
  }

  // 3.返回Promise
  // promise then function exec: hehehehe
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("hehehehe")
    }, 2000)
  })
}

// 异步函数的返回值一定是一个Promise
const promise = foo()
promise.then(res => {
  console.log("promise then function exec:", res)
})

异步函数和普通函数的区别-异常

异步函数中的异常会被作为promise的reject的值

async function foo() {
  console.log("foo function start~")

  console.log("中间代码~")

  // 异步函数中的异常, 会被作为异步函数返回的Promise的reject值的
  throw new Error("error message")

  console.log("foo function end~")
}

// 异步函数的返回值一定是一个Promise
foo().catch(err => {
  console.log("err:", err)
})

await关键字

  • async函数另外一个特殊之处就是可以在它内部使用await关键字,而普通函数中是不可以的。
  • await关键字有什么特点呢? 通常使用await是后面会跟上一个表达式,这个表达式会返回一个Promise; 那么await会等到Promise的状态变成fulfilled状态,之后继续执行异步函数;
  • 如果await后面是一个普通的值,那么会直接返回这个值;
  • 如果await后面是一个thenable的对象,那么会根据对象的then方法调用来决定后续的值;
  • 如果await后面的表达式,返回的Promise是reject的状态,那么会将这个reject结果直接作为函数的Promise的 reject值;

代码演示

// 1.await 跟上表达式
function requestData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(222)
      // reject(1111)
    }, 2000);
  })
}

async function foo() {
   const res1 = await requestData()
   console.log("后面的代码1", res1)
   console.log("后面的代码2")

   const res2 = await requestData()
   console.log("res2后面的代码", res2)
}
// 依次打印
// 后面的代码1 222
// 后面的代码2
// res2后面的代码 222

// 2.跟上其他的值
async function foo() {
   const res1 = await 123
   // 返回值 res1: 123
   const res1 = await {
        then: function(resolve, reject) {
            resolve("abc")
        }
   }
   // 返回值 res1: abc
   const res1 = await new Promise((resolve) => {
       resolve("why")
   })
   // 返回值 res1: why
   console.log("res1:", res1)
   
}

// 3.reject值
async function foo() {
  const res1 = await requestData()
  console.log("res1:", res1)
}

foo().catch(err => {
  console.log("err:", err)
})


阅读量:2018

点赞量:0

收藏量:0