promise写法
function myPromise(isReject,val){
return new Promise((resolve,reject) => {
isReject? reject('err'):
setTimeout(resolve,2000,val)
setTimeout(()=>{
resolve(val)
},5000)
})
}
generator写法
function * myGenerator() {
yield myPromise(false,1)
}
console.log(myGenerator().next())
console.log(myGenerator().next().value.then((res) => console.log(res)))
Async/await写法
var myasync = async function() {
var value1 = await myPromise(false,2)
return value1
}
console.log(myasync().then(res => console.log(res)))
generator和普通函数的区别
function* sum(x) {
var y = yield x +2;
return y;
}
var val = sum(1);
console.log( val.next())
console.log( val.next())
function* sum(){
var result = yield myPromise(false,3);
console.log(result);
}
sum.next().value.then(res => console.log(res))
- 普通函数没有*标志,这是
generator
函数的标志 - 普通函数调用会返回结果,
generator
函数调用不会返回结果,返回的是指针对象val,这个对象有两个值value,done
,values
就是yield
语句后面的表达式的值,done
只有遇到return
才会变成true
Async和generator的区别
var sum = async function (){
var value2 = await myPromise(false,4);
return value2;
};
async
只是generator
的一个语法糖,他相当于*,await
相当于yield
async
和 await
,比起星号和 yield
,语义更清楚了yield
命令后面只能是 Thunk
函数或 Promise
对象,而 async
函数的 await
命令后面,可以跟 Promise
对象和原始类型的值(数值、字符串和布尔值,但这时等同于同步操作)
三者关系
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200517114028781.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1lNWDIwMjA=,size_16,color_FFFFFF,t_70#pic_center)
generator
和async/await
是基于promise
的