ES6之async、await基础用法_async是es几
1、async/await场景
用同步的思维来解决异步问题的方案,当前端接口调用需要等到接口返回值以后渲染页面时;
2、基本理解
- async 函数返回的是一个promise 对象,如果要获取到promise 返回值,我们应该用then 方法;
async function timeout() {
return 'hello world'
}
timeout().then(result => {
console.log(result);
})
console.log('虽然在后面,但是我先执行');
- 如果async 函数中有返回一个值 ,当调用该函数时,内部会调用Promise.resolve() 方法把它转化成一个promise 对象作为返回,但如果timeout 函数内部抛出错误呢? 那么就会调用Promise.reject() 返回一个promise 对象。
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 对象。
函数内部抛出错误, promise 对象有一个catch 方法进行捕获
timeout(false).catch(err => {
console.log(err)
})
- 注意await 关键字只能放到async 函数里面
async function testResult() {
let result = await doubleAfter2seconds(30);
console.log(result);
}
await 表示等一下,代码就暂停到这里,不再向下执行了,它等什么呢?等后面的promise对象执行完毕,然后拿到promise resolve 的值并进行返回,返回值拿到之后,它继续向下执行。
这时你看到了then 的链式写法,有一点回调地域的感觉。