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

每个项目产品都会让你加埋点,你是愿意花几天一个个加,还是愿意几分钟一个小时加完去喝茶聊天?来试试这520web工具, 高效加埋点,目前我们公司100号前端都在用,因为很好用,所以很自然普及开来了,推荐给大家吧

http://www.520webtool.com/

自己开发所以免费,埋点越多越能节约时间,点两下埋点就加上了,还不会犯错,里面有使用视频,反正免费 😄

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 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值