【JS学习】ES6之async和await
作用
async
和await
是用来处理异步的。即你需要异步像同步一样执行,需要异步返回结果之后,再往下依据结果继续执行。
async
是“异步”的简写,而 await
可以认为是 async wait
的简写。
async
用于申明一个 function
是异步的,而 await
用于等待一个异步方法执行完成。
async
testAsync().then(v => {
console.log(v); // 输出 hello async
});
当 async
函数没有返回值时,返回 Promise.resolve(undefined)
await
await
只能放在async
函数内部使用
await
用于一个异步操作之前,表示要“等待”这个异步操作的返回值。
await
也可以用于一个同步的值。
如果它等到的不是一个 Promise
对象,那 await 表达式的运算结果就是它等到的东西。
如果它等到的是一个 Promise
对象,await
就会阻塞后面的代码,等着 Promise
对象 resolve
,然后得到 resolve
的值,作为 await
表达式的运算结果。
同步代码
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
})
}
async function testResult () {
let result = await doubleAfter2seconds(30);
console.log(result);
}
testResult();
// 2s 之后,输出了60.
执行顺序
案例一
console.log("1")
异步处理函数:console.log(2)
console.log(3)
结果
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
})
}
async function testResult () {
let first = await doubleAfter2seconds(10);
let second = await doubleAfter2seconds(20);
console.log(first + second);
}
错误处理
方式一 统一处理
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
})
}
async function testResult () {
try {
let first = await doubleAfter2seconds(10);
let second = await doubleAfter2seconds(20);
let res = first + second;
return res;
} catch (error) {
console.log(error);
}
}
testResult()
在接口中使用(axios)
created () {
this.init()
},
methods: {
async init () {
try {
let first = await this.getOne();
let second = await this.getTwo();
let res = first + second;
console.log(res);
} catch (error) {
console.log(error);
}
},
getOne () {
const params = {name: 'one'}
return new Promise((resolve, reject) => {
axios.get('/one', { params}).then((res) => {
if (res.status === 200) {
resolve(res)
}
}).catch((err) => {
reject(err)
})
})
},
getTwo () {
const params = {name: 'two'}
return new Promise((resolve, reject) => {
axios.get('/two', { params}).then((res) => {
if (res.status === 200) {
resolve(res)
}
}).catch((err) => {
reject(err)
})
})
},
},
作者:lesdom
链接:https://www.jianshu.com/p/4e91c4be2843
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。