关于async/await的小悟

关于async/await的小悟

  • 须要具有的前置知识
  • 对于 async/await 理解

须要具有的前置知识

对于 async/await 理解

简述

带 async 的函数(async function fn(){}),会返回 Promise 函数javascript

  • 若是 fn 返回的是 promise,就直接返回该 promise
  • 若是 fn 返回的不是 promise,则调用 Promise.resolve()转成 promise 后返回

await 至关于 promise 构造函数中的 resolve 参数java

  • await 只能在 async 中使用,而 resolve 在 promise 构造函数中使用
  • await 等待到的右侧表达式(promise 或其余)的值将做为 promise 中的终值(value)
  • await 运算符是个从右往左运算的运算符
    • resolve 函数调用时也要先计算参数表达式的值
    • 反向思考,若是不先计算右侧表达式,那么 await(等待)的表达式就没有触发的时机啦
  • await 和 resolve 不一样的地方就是 await 会把后面的全部操做都“转移”到 then 中操做,由于 await 具备阻塞的效果

表达式表示

async function fn(){
code1...;
const value=await fn2();
code2...;
}
复制代码

类等于es6

new Promise(resolve=>{
code1...;
resolve(fn2());
}).then(value=>{
code2...;
})
复制代码

示例比较打印是否相同

  • 示例 1(同步方法):
function syncFun() {
  console.log('syncFun start')
  return 'value'
}
async function asyncFun() {
  console.log('async start')
  const value = syncFun()
  console.log('value=' + value)
  console.log('async end')
}
asyncFun()
console.log('main end')
复制代码
function syncFun() {
  console.log('syncFun start')
  return 'value'
}
new Promise(resolve => {
  console.log('promise start')
  const value = syncFun()
  console.log('value=' + value)
  console.log('promise end')
})
console.log('main end')
复制代码
  • 示例 2(异步方法-接收数值):
function syncFun() {
  console.log('syncFun start')
  return 'value'
}
async function asyncFun() {
  console.log('async start')
  const value = await syncFun()
  console.log('value=' + value)
  console.log('async end')
}
asyncFun()
console.log('main end')
复制代码
function syncFun() {
  console.log('syncFun start')
  return 'value'
}
new Promise(resolve => {
  console.log('promise start')
  resolve(syncFun())
}).then(value => {
  console.log('value=' + value)
  console.log('promise end')
})
console.log('main end')
复制代码
  • 示例 3(异步方法-接收 promise):
async function syncFun() {
  console.log('syncFun start')
  return 'value'
}
async function asyncFun() {
  console.log('async start')
  const value = await syncFun()
  console.log('value=' + value)
  console.log('async end')
}
asyncFun()
console.log('main end')
复制代码
async function syncFun() {
  console.log('syncFun start')
  return 'value'
}
new Promise(resolve => {
  console.log('promise start')
  resolve(syncFun())
}).then(value => {
  console.log('value=' + value)
  console.log('promise end')
})
console.log('main end')
复制代码

后话

没看过 async/await 的源码,只是根据使用的时候的直觉而写,若有不妥之处,欢迎指正(欢迎加微信 772345373)segmentfault

相关文章
相关标签/搜索