async、await的用法
function call(){
console.log('call funtion');
return new Promise(resolve=>{
setTimeout(function(){
console.log('call funtion timeout');
resolve('dd');
},1000);
});
}
function normalFunction() {
console.log('normalFunction');
return 'data'
}
// call(function(){
// console.log('callback');
// });
async function asynctest() {
console.log('start');
await call();
await normalFunction();
await new Promise(resolve=>{ console.log('wait result'); resolve()});
console.log('end');
}
asynctest();
执行结果
PS F:\zzj1026\Rnx\testEgg> node .\async.js
start
call funtion
call funtion timeout
normalFunction
wait result
end
PS F:\zzj1026\Rnx\testEgg>
个人理解 async是说明这个function是异步的await这个关键字是阻塞(将函数挂起,等待返回结果),如果返回值是promise则等待promise的resolve或reject的结果,如果是函数返回的普通值直接往下执行
yield使用
function call(){
console.log('call funtion');
return new Promise(resolve=>{
setTimeout(function(){
console.log('call funtion timeout');
resolve('dd');
},1000);
});
}
function normalFunction() {
console.log('normalFunction');
return 'data'
}
function* yieldFunc() {
console.log('start');
yield call();
yield normalFunction();
console.log('end');
}
let yieldData=yieldFunc();
let firstData=yieldData.next();
console.log(firstData);
firstData.value.then(function(data){
console.log(data);
});
yieldData.next();
console.log(yieldData);
执行结果
PS F:\zzj1026\Rnx\testEgg> node .\async.js
start
call funtion
{ value: Promise { <pending> }, done: false }
normalFunction
{}
call funtion timeout
dd
PS F:\zzj1026\Rnx\testEgg>
个人理解: 函数执行每次都执行到yield这里返回一个yield阻塞的值{ value: Promise { }, done: false },这个时候就可以处理值了,然后如果done为true时表示这个函数已经执行完成了