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>

--------------------- 
作者:米斯特尔曾 
来源:CSDN 
原文:https://blog.csdn.net/qq_30101131/article/details/79463258 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/sd19871122/article/details/85160141