快速連結

2021年10月17日

[筆記]Async & Await 基本用法

異步顯示:

    @property(cc.Label)
    private label: cc.Label = null;

    start () {
        this.FirstProcess();
    }

    private async FirstProcess(){
        this.label.string = "===== First Line =====\n";
        this.DoShowMessage(0);
        this.label.string += "===== Second Line =====\n";
        await this.DoShowMessage(0.5);
        this.label.string += "===== Finished =====\n";
    }

    private async DoShowMessage(num: number){
        let a = await this.GetDelayValue(num + 1);
        this.ShowMessage(a);
        let b = await this.GetDelayValue(num + 2);
        this.ShowMessage(b);
    }

    private GetDelayValue(n:number){
        return new Promise(resolve => {
            setTimeout(()=> resolve("line " + n +
                     "(delay "+ n +" secs)"), n * 1000);
        });        
    }

    private ShowMessage(s){
        this.label.string += s + "\n";
    }

沒有留言:

張貼留言

歡迎大家留言提問,我會答的都會盡力回答!
如果太久沒出現回應就是我又忘記回來看留言了TAT