溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

TypeScript之異步函數(shù)

發(fā)布時間:2020-07-03 07:46:13 來源:網(wǎng)絡 閱讀:9862 作者:Aonaufly 欄目:開發(fā)技術

必須搞清楚 setTimeout 為異步函數(shù).
因為 : TS中沒有線程休眠 , 所以我提供了如下測試方式

一 : 正常

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

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

        /**
         * 測試異步回調函數(shù)
         * @param {string} $name
         */
        private async getSomething( $name : string ) : Promise<string>{
            egret.log(`開始執(zhí)行異步函數(shù)`);
            this._sentry = 1;
            const $id = await this.timeout();
            egret.log(`timeout 執(zhí)行完畢! timeid : ${$id}`);
            return $name;
        }

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

    }
}

結果 :
TypeScript之異步函數(shù)

解釋 : setTimeOut是異步的

二 :
TypeScript之異步函數(shù)

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

結果:
TypeScript之異步函數(shù)

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

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

下面有三個使用到Prmomise的例子
第1個例子 使用 new Promise,體現(xiàn)了 promise實現(xiàn)異步機制
2和3 使用 Promise.resolve
第3個例子,通過 then 將 參數(shù)傳遞到下一個 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方法
   //這里很好地體現(xiàn)了 Promise實現(xiàn)了 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 );
            }
        }
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI