vue中用 async/await 来处理异步

async 的语法

1、它作为一个关键字放在函数前面,用于表示函数是一个异步函数,因为async就是异步的异步,异步函数也就是意味着这个函数的执行不会阻塞后面代码的执行。简单的写一个async函数:

async function timeout(){
  return 'hello world';
}

timeout();
console.log('虽然在后面,但是我先执行');

打开浏览器控制台,我们看到了

 

2、async 函数 timeout  调用了,但是没有任何输出,它不是应该返回 'hello world',  先不要着急, 看一看timeout()执行返回了什么? 把上面的 timeout() 语句改为console.log(timeout()).

async function timeout() {
    return 'hello world'
}
console.log(timeout());
console.log('虽然在后面,但是我先执行');

继续看控制台

3、原来async 函数返回的是一个promise 对象,如果要获取到promise 返回值,我们应该用then 方法, 继续修改代码

async function timeout() {
    return 'hello world'
}
timeout().then(result => {
    console.log(result);
})
console.log('虽然在后面,但是我先执行');

看控制台

  我们获取到了"hello world',  同时timeout 的执行也没有阻塞后面代码的执行,和我们刚才说的一致。

  这时,你可能注意到控制台中的Promise 有一个resolved,这是async 函数内部的实现原理。如果async 函数中有返回一个值 ,当调用该函数时,内部会调用Promise.solve() 方法把它转化成一个promise 对象作为返回,但如果timeout 函数内部抛出错误呢? 那么就会调用Promise.reject() 返回一个promise 对象, 这时修改一下timeout 函数

async function timeout(flag) {
    if (flag) {
        return 'hello world'
    } else {
        throw 'my god, failure'
    }
}
console.log(timeout(true))  // 调用Promise.resolve() 返回promise 对象。
console.log(timeout(false)); // 调用Promise.reject() 返回promise 对象。

 

posted @ 2021-09-08 17:02  小阿飞ZJF  阅读(664)  评论(0编辑  收藏  举报