关于前端:async和await-如何使用

11次阅读

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

async 和 await 是 ES7 引入的新语法,能够更加不便的异步操作

async 关键字用在函数上 (async 函数的返回值是 promise 实例对象)

await 必须跟 async 同时应用。

例子:

// 获取数据 1
    getDatas1() {return new Promise((resolve, reject) => {
        this.$http
          .get(window.SITE_CONFIG.apiURL + "/static/queryStatic", {
            params: {dictType: "accept_promotion",},
          })
          .then((res) => {
            let result = res.body.data;
 
            this.ycslArr1 = result;
            resolve("嘿嘿嘿 1")
          })
        .catch(() => {});
      });
    },
    
// 获取数据 2
    getDatas2() {return new Promise((resolve, reject) => {
        this.$http
          .post(window.SITE_CONFIG.apiURL + "/service656", {
            machineCode: "SfJjeyP0xmnS6h8R",
            url: "/power/getItemCountByOnlineDepth/1.0",
            postdata: {},})
          .then((res) => {let result = JSON.parse(res.body.result).data;
            this.wbsdData2.pop();
            resolve("嘿嘿嘿 222");
          })
          .catch(() => {});
      });
    },
    
     async query() {let ret1 = await this.getDatas1();
      var ret2 = await this.getDatas2();
      console.log("ret1????", ret1, ret2); // 嘿嘿嘿 1, 嘿嘿嘿 222
    },
正文完
 0