Coroutine in Cocos Ceator?

js and ts no real coroutine。You need to stop asynchronous logic through code control, such as this

start () {

    this.startCountDown();
},

async sleep(seconds){
	return new Promise((resole) => setTimeout(resole, seconds * 1000));
},

async startCountDown() {
    this._isStartCountDown = true;

    await this.sleep(1);

    if(this._isStartCountDown){

	    cc.log('checkEndGame')
	    //this.checkEndGame();

	    this.startCountDown();
    }
},

stopCountDown(){
	this._isStartCountDown = false;
},
1赞

thanks for your idea.
I will try another idea hope the better way :slight_smile:
Thanks!

How about

stoppable (task: Promise): Promise {
    return new Promise((resolve, reject) => {
        task.catch(e => reject(e));
        task.then(value => {
            // check component destroyed state or use any other condition to stop coroutines
            if (this.isValid) {  
                resolve(value);
            }
            else {
                // DONT CALLBACK
            }
        });
    });
}

async start () {
    await foo();  // unstoppable
    console.log('output');

    await stoppable(bar);
    console.log('never output if destroyed');
}

You can even write a decorator, like

@stoppable
async foo () {
}

async start () {
    await foo();
    console.log('never output if destroyed');
}
1赞
function* startCountdown() {
  this._isStartCountDown = false;
  yield;
  this.checkEndGame();
  this._isStartCountDown = true;
}

const manager = startCountdown();
manager.next(); // this._isStartCountDown === false
// sleep or do anything....
manager.next(); // this._isStartCountDown === true
3赞

个人觉得 rxjs 比 async & await 好用多了.

这些异步语法糖乍一看很美好, 实际应用起来很容易陷入状态错乱问题.

rxjs 一个 takeUntil 可以避免大部分状态错乱问题.

Thank you. The great idea :smiley:
I will try!

Wow, i don’t think ts have this thing!
I will try it!
Thank you!

Can i ask a question about : what’s better way to stop/delete a Generator function?

Consume it. Or let your generator itself return at some where.

1赞

I think you are amazing. Can you add a friend?

I’m not :slight_smile:
And of course we’re all friend :))

Can you explain it clearly? :))

还有这种写法?我也是第一次见,刚刚在vscode里试了一下还真的不报错,牛逼,后面具体我再试试。

这种用法不会造成内存泄漏么

不会。。。

持有的 promis 没有终止啊 , 这没有内存泄漏的问题??

我的错,这里 DONT CALLBACK 处应该 reject 一个特定的异常,由上层调用处去进行捕获才行。

comp 中 await函数后面如果 继续处理 this相关对象,但是 这个组件又被销毁了 。那就会报错。
这个有什么通用处理方法能够阻断代码继续执行。

Promise.race

async function(){
await this.fucA();
await this.funcB();
}

等待funcA 执行过程中 comp 销毁了。 怎么让代码不继续执行 funcB;
@jare