关于javascript:异步函数的使用

9次阅读

共计 681 个字符,预计需要花费 2 分钟才能阅读完成。

简介

阮一峰 ES6
ES2017 引入 async 函数, 它是 Generator 函数的语法糖。
async 函数返回一个 Promise 对象,能够应用 then 办法增加回调函数。
await 命令只能用在 async 函数之中,如果用在一般函数,就会报错。
失常状况下,await 命令前面是一个 Promise 对象,返回该对象的后果。如果不是 Promise 对象,就间接返回对应的值。
await 命令前面的 Promise 对象,运行后果可能是 rejected,所以最好把 await 命令放在 try…catch 代码块中。

   async goStore() {
      try {const { code, data} = await downIos()

        if (code == 0) {window.location.href = data.downloadUrl}
      } catch (error) {}},


   downIos = (params = {}) => {
    return service.requestD({
      url: '/version/ios/downloadInfo',
      method: 'post',
      data: params,
    });

多个 await 命令前面的异步操作同时触发

let foo = await getFoo();
let bar = await getBar();

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

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

正文完
 0