TypeScript之異步函數

必須搞清楚 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秒`);
        }

    }
}

結果 :
TypeScript之異步函數

解釋 : setTimeOut是異步的

二 :
TypeScript之異步函數

因爲 : await 關鍵字 , 是等待 this.timeout()的結果 , 他是永遠等不到的 , 所以程序卡死

結果:
TypeScript之異步函數

這個和 C# 是一樣的 , 只不過C#好測試 , 因爲C#有線程的概念!!!

其他補充 : https://blog.csdn.net/rcjjian/article/details/72831577

下面有三個使用到Prmomise的例子
第1個例子 使用 new Promise,體現了 promise實現異步機制
2和3 使用 Promise.resolve
第3個例子,通過 then 將 參數傳遞到下一個 then
將代碼複製 運行,就會看到 promise的奧祕

//new Promise() vs Promise.resolve()
//then 方法每次都會返回 promise實例對象

function newPromise_resolve() {
   return new Promise((resolve,reject) => {
      resolve(); //這裏調resolve方法,則then方法會被調用
      console.log('resolve裏面的log');
   })
   //先輸出 resolve裏面的log
   //後輸出 then方法
   //這裏很好地體現了 Promise實現了 node.js的異步機制
}

newPromise_resolve().then(() => {
   console.log('then方法');
});

newPromise_resolve();

//使用Promise.resolve
function promise_resolve() {
   let promise = Promise.resolve();
   promise
   .then(() => {
      console.log('promise_resolve1');
   })
   .then(() => {
      console.log('promise_resolve2');
   });

   return promise;
}

//promise_resolve(); 

function promise_forEach_then() {
   let ids = [1,2,3];
   let promise = Promise.resolve();
   ids.forEach((id) => {
      promise
      .then(() => {
         return {id}
      })
      .then(consoleLogId)
   });
}

function consoleLogId(id) {
   console.log('promise_forEach_then---' + id);
}

//promise_forEach_then();

///////////////////////////////////////

        public deatoryGroupRes( $groupName : string ) : Promise<boolean>{
            if( this._hashmap.containsKey( $groupName ) == true ){
                if( this._is_loading == true && $groupName == this._cur_group ){
                    return new Promise((resolve,reject) : void=>{
                        resolve(false);
                                                reject(false);
                    });
                }else{
                    this._hashmap.remove( $groupName );
                    return RES.destroyRes( $groupName );
                }
            }else{
                return RES.destroyRes( $groupName );
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章