TypeScript Async相容測試

前言
   前幾天與同事在測試某段javascript時,看到 async關鍵字,心想怎麼前端會有這種東東,可以執行非同步....,Google一下後,才知道在ECMA 2017就開始支援了..。
目前的專案使用的是TypeScript+ECMA 5.0,不敢冒然升級ECMA 6+ ~ 2021,因為有年代久遠的裝置,要考慮其相容性。

  在不想升級ECMA,又想使用async 等ECMA新功能,該怎麼辨? 別擔心! 舞照跳、酒照喝XD,TypeScript的編譯器會幫你搞定一切,接下來的測試,會說明。

測試
TypeScript - 原始版本 :程式碼會往後端呼叫3次,等每次呼叫完,才會執行下一個
    Lab() {
            console.log("Lab-Start");
            this.AllFunctionsService.GetFunctions((response) => {
                console.log("  Lab-GetFunctions 1");
                this.AllFunctionsService.GetFunctions((response) => {
                    console.log("  Lab-GetFunctions 2");
                    this.AllFunctionsService.GetFunctions((response) => {
                        console.log("  Lab-GetFunctions 3");
                        console.log("Lab-End");
                    });
                });
            });
       
        }

執行結果
TypeScript - async版本 : await了3次的GetFunction,最後才執行到End,結果同上圖。看起來是不是簡單好維護多了~~~
        async Lab() {
            console.log("Lab-Start");
            await this.AllFunctionsService.GetFunctions((response) => {
                console.log("  Lab-GetFunctions 1");
            });
            await this.AllFunctionsService.GetFunctions((response) => {
                console.log("  Lab-GetFunctions 2");
            });
            await this.AllFunctionsService.GetFunctions((response) => {
                console.log("  Lab-GetFunctions 3");
            });
            console.log("Lab-End");
        }

JavaScript的差異
感受一下TypeScript在ECMA不同版本下的差異。

ECMA 2017+ : 跟TypeScript一致
ECMA 5 : 產生了awater 程式碼,實作出非同步效果

其它參考
  • https://ithelp.ithome.com.tw/articles/10241334

這個網誌中的熱門文章

IIS 設定只允許特定IP進入