generator函数是一个状态机,封装了多个内部状态
或者理解程是一个遍历器对象生成函数
执行generator函数会返回一个遍历器对象
返回的遍历器对象,可以依次遍历Generator函数内部的每一个状态
function* helloWorld(){
yield 'hello';
yield 'world';
return 'ending'
}
var hw = helloWorld
hw.next()
async函数对Generator函数的改进,体现在一下四点
(1)内置执行器 // async函数的执行方式
(2)语义化
(3)更广的适用性
(4)返回值是promise
async函数的返回值是promise对象
Generator函数的返回值是Iterator对象
// async函数完全可以看作是多个异步操作,包装成的一个promise对象,而await命令就是内部then命令的语法糖
2:基本用法
async函数返回一个promise对象,可以使用then方法添加回调函数,当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体后面的语句
async function getStockPriceByName(name) {
const symbol = await getStockSymbol(name)
const stockPrice = await getStockPrice(symbol)
return stockPrice
}
getStockPriceByName('goog').then(result => {
console.log(result)
})
举个🌰
function timeout(ms){
return new Promise( resolve=>{
setTimeout(resolve,ms)
})
}
async function(){
await timeout(ms)
console.log(value)
}
async函数的多种使用形式
// 函数声明
async function(){}
// 函数表达式
const foo = async function(){}
//对象的方法
let obj = {async foo(){}};
obj.foo().then()
// class 的方法
class Storage {
constructor(){
this.cachePromise = caches.open('avatars');
async getAvatar(name){
const cache = await this.cachePromise;
return cache.match('')
}
}
}
const storage = new Storage();
storage.getAvatar('jake').then(...)
//箭头函数
const foo = async () => {};
3:async语法相关
(1)async函数返回一个promise对象
async函数内部return语句返回的值,会成为then方法回调函数的参数
async function f(){
return 'hello world'
}
f().then(v=>{console.log(v)})
Promise对象的状态变化
async函数返回的promise对象,必须等到内部所有await命令后面的promise对象执行完,才会发生变化
await命令
正常情况下,await命令后面是一个promise对象,该返回该对象的结果,如果不是promise对象,就直接返回对应的值
class Sleep{
constructor(timeout){
this.timeout = timeout
}
then(resolve,reject) {
const startTime = Date.now();
setTimeout( ()=>resolve(Date.now()-startTime)
this.timeout
)
}
}
(async()=>{
const sleepTime = await new Sleep(1000);
console.log(sleepTime);
})()
任何一个await语句后面的promise对象变为reject状态,那么整个async函数都会中断执行
async function f(){
await Promise.reject('出错了');
await Promsie.resolve('hello world')
}
有时我们希望即使前面一个异步操作失败,也不要中断后面的异步操作,这时候可以将第一个await放在try...catch结构里面,这样不管这个异步操作是否成功,第二个await都会执行
async function f(){
try {
await Promise.reject(‘error’)
} catch(e){
}
return await Promise.resolve('hello')
}
f().then(v=>console.log(v))
另一个方法是await后面的promise对象在跟一个catch方法
async function f() {
await Promise.reject('出错了')
.catch(e => console.log(e));
return await Promise.resolve('hello world');
}
f()
.then(v => console.log(v))
// 出错了
// hello world
4: async函数的实现原理
封装了generator函数和自动执行器
async function fn(args){
}
function fn(args){
return spawn(function* (){
});
}
// spawn 自动执行器
5:与其他异步处理方法的比较
async && promise && Generator