async/await

104 阅读1分钟

原理

  • 总结: async + await 原理就是 Generator + yield 的语法糖。
  • generator: 写法: function关键字和方法名之间有个*,函数内部使用yield表达式。

整个 generator 函数就是一个封装的异步任务,异步操作需要暂停的地方,都用 yield 语句注明。generator 函数的执行方法如下:

function* generator(){
  yield 'aa'  //yield类似暂停的功能
  yield 'bb'
  return 'cc'
}

let g = generator()
console.log(g.next());
console.log(g.next());
console.log(g.next());

// { value: 'aa', done: false }
// { value: 'bb', done: false }
// { value: 'cc', done: true }

async理解

使用 async 关键字,把它放在函数声明之前,使其成为 async function。 async function执行会返回一个promise

async function hello() { return `hello` }
console.log(hello)
console.log(hello())
hello().then(res => console.log(`res:`,res))

//[AsyncFunction: hello]
// Promise { 'hello' }
// res: hello