在面试的时候,async/await
是很能看出应试者知识面的一个点。固然本身也没想好从什么角度去阐释这个知识点。当面试管问的时候,你能够答自执行的generator的语法糖。可是本身有些过实现么,或者是看过他的实现。面试
注:对于generator不了解的,能够先去看一下generator,顺带能够把iterator看了。promise
ex代码:babel
async function t() {
const x = await getResult();
const y = await getResult2();
return x + y;
}
复制代码
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this, args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function t() {
return _t.apply(this, arguments);
}
function _t() {
_t = _asyncToGenerator(function* () {
const x = yield getResult();
const y = yield getResult2();
return x + y;
});
return _t.apply(this, arguments);
}
复制代码
从代码中能够看出,babel将一个generator转化为async用了两步_asyncToGenerator
和asyncGeneratorStep
。app
_asyncToGenerator
干了什么一、调用_asyncToGenerator
返回了一个promise,恰好符合async函数能够接then的特性。异步
二、定义了一个成功的方法_next
,定义了一个失败的方法_throw
。两个函数中是调用asyncGeneratorStep
。看完asyncGeneratorStep
就知道这实际上是一个递归。async
三、执行_next
。也就是上面说的自执行的generator。函数
asyncGeneratorStep
干了什么一、try-catch去捕获generator执行过程当中的错误。若是有报错,async函数直接是reject状态。优化
二、判断info中的done值,是否为true,为true就表明迭代器已经执行完毕了,能够将value值resolve出去。反之,则继续调用_next
将值传递到下一个去。ui
这里我惟一没有看明白的是`_throw`,这个看代码像是执行不到的。promise.resolve状态值应该是fulfilled。看懂的能够在评论中和我说一下,感谢。 this
每当一种新的语法糖出现,一定是弥补上一代解决方案的缺陷。
ex:
promise的出现,是为了去避免callback hell
,避免的方式就是链式调用。
那async/await为了去解决什么呢?
async/await更贴近于同步性的风格,而promise则是用then的方式,于async/await相比,代码会变多,并且async/await和同步函数差异不大,promise则写法上仍是有差距的。
promise版
function getData() {
getRes().then((res) => {
console.log(res);
})
}
复制代码
async/await版
const getData = async function() {
const res = await getRes();
console.log(res);
}
复制代码
用promise的时候会发现,多个promise串行的时候,后面的promise须要去获取前面promise的值是很是困难的。而async刚好解决了这个点。
const morePromise = () => {
return promiseFun1().then((value1) => {
return promiseFun2(value1).then((value2) => {
return promiseFun3(value1, value2).then((res) => {
console.log(res);
})
})
})
}
复制代码
上面是嵌套版本的,可能根据不一样的需求能够不嵌套的。
const morePromise = () => {
return promiseFun1().then((value1) => {
return promiseAll([value1, promiseFun2(value1)])
}).then(([value1, value2]) => {
return promiseFun3(value1, value2).then((res) => {
console.log(res);
})
})
}
复制代码
少了嵌套层级,可是仍是不尽如人意。
const morePromise = async function() {
const value1 = await promiseFun1();
const value2 = await promiseFun2(value1);
const res = await promiseFun3(value1, valuw2);
return res;
}
复制代码
串行的异步流程,一定会有中间值的牵扯,因此async/await的优点就很明显了。
好比,目前有个需求,你请求完一个数据以后,再去判断是否还须要请求更多数据。用promise去实现仍是会出现嵌套层级。
const a = () => {
return getResult().then((data) => {
if(data.hasMore) {
return getMoreRes(data).then((dataMore) => {
return dataMore;
})
} else {
return data;
}
})
}
复制代码
可是用async去优化这个例子的话,能使代码更加优美。
const a = async() => {
const data = await getResult();
if(data.hasMore) {
const dataMore = await getMoreRes(data);
return dataMore;
} else {
return data;
}
}
复制代码
上面咱们讲了几点async/await的优点所在,可是async/await也不是万能的。上面清一色的是讲串联异步的场景。当咱们变成并联异步场景时。仍是须要借助于promise.all来实现
const a = async function() {
const res = await Promise.all[getRes1(), getRes2()];
return res;
}
复制代码
async/await在错误捕获方面主要使用的是try-catch。
const a = async () => {
try{
const res = await Promise.reject(1);
} catch(err) {
console.log(err);
}
}
复制代码
能够抽离一个公共函数来作这件事情。由于每一个promise后面都去作catch的处理,代码会写的很冗长。
const a = async function() {
const res = await Promise.reject(1).catch((err) => {
console.log(err);
})
}
复制代码
// 公共函数
function errWrap(promise) {
return promise().then((data) => {
return [null, data];
}).catch((err) => {
return [err, null];
})
}
复制代码