js 关于async await的问题?

created () {
  this.init()
},
methods: {
  init () {
    this.getToken()
    this.getData()
  },
  async getToken () {
    let token = await postToken()
    ...
  },
  async getData () {
    if(this.token) return 'token no null'
    let data = await postData();
    ....
  }
}

代码大致如上,实际运行时总是报'token no null',不是已经给两个用到ajax方法加async await了吗,为什么还是异步?

阅读 2.1k
3 个回答
  async init () {
    await this.getToken()
    this.getData()
  },

那是在getToken方法和getData方法内部,你init方法又不是......

Async/Await本身就是用于处理异步的,await执行后只要一有结果就会返回

function timeout(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

async function asyncPrint(value, ms) {
    await timeout(ms);
    console.log(value);
}

asyncPrint('hello world', 50);

上面代码指定50毫秒以后,输出hello world。

如果想要指定其请求时间,再返回值可以设定等候时间。
参考:
ES6系列文章 异步神器async-await
理解 JavaScript 的 async/await

推荐问题