async

87 阅读1分钟
function fetchData() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('success')
      }, 2000)
    })
  }
async function fn1() {
    console.log('fn1---start');
    await fetchData()
    console.log('fn1---end');
}

function fn2() {
    fn1()
    console.log('fn2---end');
}

fn2()
  
//fn1---start
//fn2---end
//fn1---end
  • 以上代码若需 fn2---end最后打印需要改写成以下方式
function fetchData() {
return new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  }, 2000)
})
}
async function fn1() {
console.log('fn1---start');
await fetchData()
console.log('fn1---end');
}

async function fn2() {
await fn1()
console.log('fn2---end');
}

fn2()
  • async必须在await的最近的方法的外层
mounted() {
    this.getSysTime(res => {
       const timeId = setInterval(async () => { // 注意这个async需要写在这里
            await this.request();
        }, 1000);
});
    },