1. 程式人生 > >TypeScript之異步函數

TypeScript之異步函數

egret async await 異步

必須搞清楚 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之異步函數