JS 中的 async / await
1、async / await 是什么
可以说是 ES6 中 Generator 函数的语法糖,async 是异步的意思 , await 是等待的意思 ,连起来就是等待一个异步函数,规定 await 只能出现在 async 函数中
2、async / await 的作用
我们先看如果在一个 async 函数中直接用 return 返回值, 看能得到什么
async function testAsync() {
return "hello async" ;
}
const res = testAsync()
console.log(res) // Promise { 'hello async' }
最后返回的是一个 promise 对象,这说明 async 函数返回的是一个 promise 对象, 如果 return 一个直接量 , async 会把这个直接量通过 Promise.resolve() 封装成 Promise 对象然后返回,这就是 async 函数的作用
那我们再来看看 await 的作用
function getSomething() {
return "something";
}
async function testAsync() {
return Promise.resolve("hello async");
}
async function test() {
const v1 = await getSomething();
const v2 = await testAsync();
console.log(v1, v2);
}
test(); // something hello async
await 等的就是它后面表达式的结果,可以是 Promise 对象 也可以不是,
如果不是一个 Promise 对象, await 表达式的运算结果 就是它等的结果
如果是一个 Promise 对象, await 就会等着 Promise 对象 resolve , 直到得到 resolve 的值,作为 await 表达式运算的结果,await 等待的过程中,在这个函数内部会造成阻塞
3、 优势
async / await 的优势在于处理 多个 Promise 组成的 then 链 举个栗子
function takeLongTime(n) {
return new Promise(resolve => {
setTimeout(() => resolve(n + 200), n)
})
}
function step1(n) {
console.log( `step1 with ${n}`);
return takeLongTime(n)
}
function step2(n) {
console.log( `step2 with ${n}`);
return takeLongTime(n)
}
function step3(n) {
console.log( `step3 with ${n}`);
return takeLongTime(n)
}
// Promise 方式来实现这三个步骤的处理
function doIt () {
const time = 300
step1(time)
.then(time2 => step2(time2))
.then(time3 => step3(time3))
.then(res => {
console.log(res)
})
}
doIt()
// step1 with 300
// step2 with 500
// step3 with 700
// 900
//用 async/await 来实现
async function doIt () {
const time = 300
const time2 = await step1(time)
const time3 = await step2(time2)
const res = await step3(time3)
console.log(res)
}
doIt()
// step1 with 300
// step2 with 500
// step3 with 700
// 900
以上对比可以看出 async/await 来实现会使代码看起来更加清晰
4、 注意点
await 命令后面的 Promise 对象,运行结果可能是 rejected,所以最好把 await 命令放在 try…catch 代码块中
async function myFunction() {
try {
await somethingThatReturnsAPromise();
} catch (err) {
console.log(err);
}
}
// 另一种写法
async function myFunction() {
await somethingThatReturnsAPromise().catch(function (err){
console.log(err);
});
}
如有错误,欢迎指正
参考文献
http://www.ruanyifeng.com/blog/2015/05/async.html
https://segmentfault.com/a/1190000007535316