Created
April 24, 2017 03:30
-
-
Save OrionNebula/bd2d4339497a2c05e599d7d24038d290 to your computer and use it in GitHub Desktop.
Co-routines in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export abstract class BlockingAction { | |
type: string; | |
abstract setup(iter: IterableIterator<BlockingAction>): void; | |
handleNext(iter: IterableIterator<BlockingAction>): void { | |
let n = iter.next(); | |
if(n.done) | |
return; | |
n.value.setup(iter); | |
}; | |
public static startCoroutine(func: () => IterableIterator<BlockingAction>): void { | |
let iter = func(); | |
let n = iter.next(); | |
if(n.done) | |
return; | |
n.value.setup(iter); | |
} | |
} | |
export class Wait extends BlockingAction { | |
wait: number; | |
constructor(timeout : number) { | |
super(); | |
this.wait = timeout; | |
} | |
setup(iter: IterableIterator<BlockingAction>) : void { | |
let t = this; | |
setTimeout(function(){ | |
t.handleNext(iter); | |
}, this.wait); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BlockingAction, Wait } from './BlockingAction'; | |
function* coroutine() : IterableIterator<BlockingAction> { | |
let time = new Date().getTime(); | |
console.log('Time to wait for 1 second.'); | |
yield new Wait(1000); | |
console.log('This was a blocking call!'); | |
console.log('The time taken was: ' + (new Date().getTime() - time)); | |
} | |
BlockingAction.startCoroutine(coroutine); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment