首页 > 其他 > 详细

TypeScript之异步函数

时间:2018-04-04 20:41:36      阅读:370      评论:0      收藏:0      [点我收藏+]
必须搞清楚 setTimeout 为异步函数.
因为 : TS中没有线程休眠 , 所以我提供了如下测试方式

一 : 正常

module demo{
    export class AsyncDemo{
        private _sentry : number = 0;
        public start() : void{
            this.getSomething("Aonaufly").then(
                $value=>{
                    egret.log(`执行成功 ! name : ${$value}`);
                },
                $error=>{
                    egret.log(`执行失败 ! error : ${$error}`);
                }
            );
        }

        private timeout() : number{
            while( this._sentry == 0 ){
                if( this._sentry != 0 ){
                    break;
                }
            }
            return egret.setTimeout(
                this.handler_timeout,
                this,
                2500
            );
        }

        /**
         * 测试异步回调函数
         * @param {string} $name
         */
        private async getSomething( $name : string ) : Promise<string>{
            egret.log(`开始执行异步函数`);
            this._sentry = 1;
            const $id = await this.timeout();
            egret.log(`timeout 执行完毕! timeid : ${$id}`);
            return $name;
        }

        private handler_timeout() : void {
            egret.log(`执行了等待 2.5秒`);
        }

    }
}

结果 :
技术分享图片

解释 : setTimeOut是异步的

二 :
技术分享图片

因为 : await 关键字 , 是等待 this.timeout()的结果 , 他是永远等不到的 , 所以程序卡死

结果:
技术分享图片

这个和 C# 是一样的 , 只不过C#好测试 , 因为C#有线程的概念!!!

TypeScript之异步函数

原文:http://blog.51cto.com/aonaufly/2094805

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!