async、await

2020-09-23  本文已影响0人  懂会悟

1、async


2、async使用方式

// 函数声明
async function foo() {}

// 函数表达式
const foo = async function () {}

// 对象的方法
let obj = { async foo() {} }
obj.foo().then(...)

// Class 的方法
class Storage {
  constructor() {
    this.cachePromise = caches.open('avatars')
  }

  async getAvatar(name) {
    const cache = await this.cachePromise;
    return cache.match(`/avatars/${name}.jpg`)
  }
}

const storage = new Storage();
storage.getAvatar('jake').then(…)

// 箭头函数
const foo = async () => {}


3、await


4、await使用注意事项

// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;


5、补充

async 会将其后的函数(函数表达式或 Lambda)的返回值封装成一个 Promise 对象,而 await 会等待这个 Promise 完成,并将其 resolve 的结果返回出来。


上一篇 下一篇

猜你喜欢

热点阅读