javascript中async、await、yield、*的用法

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时表示这个函数已经执行完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值