async/await让异步写法像同步一样简洁。
async可以包含0个或者多个await表达式。await表达式会暂停整个async函数的进程并出让其控制权,只有当其等待的基于promise的异步操作被兑现或被拒绝之后才会恢复进程。
1、await关键字只在async函数内有效
2、async/await的目的为了简化使用基于promise的API时所需的语法。async/await的行为就好像搭配使用了生成器和promise。
3、async函数一定会返回一个promise对象。如果一个async函数的返回值看起来不是promise,那么它将会被隐式地包装在一个promise中。
例子1:
async function test (){
return 'hello'
}
console.log(test())
控制台输出:
Promise { < fulfilled> : "hello"}
这个例子可以看到aysnc返回的是一个promise对象。
如果要获取到promise 返回值,我们应该用then 方法, 继续修改代码,
例子2:
async function test(){
return 'hello'
}
test().then(res => console.log(res))
如果是抛出异常,promise有一个catch方法捕获,
例子3:
async function test(flag){
if(flag){
return 'hello'
}else{
throw 'my god,failure'
}
}
console.log(test(true))
console.log(test(false))
test(true).then(res => console.log(res))
test(false).catch(res => console.log(res))
await只能用在async中,async/await可以解决地狱回调
如果我们要计算3个数的值,然后把得到的值进行输出,应该怎么做呢?
例子4:
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
} )
}
async function testResult() {
let first = await doubleAfter2seconds(30);
let second = await doubleAfter2seconds(50);
let third = await doubleAfter2seconds(30);
console.log(first + second + third);
}
6秒后,控制台输出220, 我们可以看到,写异步代码就像写同步代码一样了,再也没有回调地域了。
关于异常处理,可以使用try/catch
例子5:
async function testResult() {
try{
let first = await doubleAfter2seconds(30);
let second = await doubleAfter2seconds(50);
let third = await doubleAfter2seconds(30);
console.log(first + second + third);
}catch(e){
...
}
}
参考自: 用 async/await 来处理异步