Created
October 20, 2023 09:22
-
-
Save JosePedroDias/69014dcad0a41282fb0b629d52ca94c9 to your computer and use it in GitHub Desktop.
multiple consumers of a promise
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
function defer<T>(): { | |
promise: Promise<T>; | |
resolve: (resp: T) => void; | |
reject: (err: any) => void; | |
} { | |
const answer: any = {}; | |
answer.promise = new Promise((resolve, reject) => { | |
answer.resolve = resolve; | |
answer.reject = reject; | |
}); | |
return answer; | |
} | |
class Producer { | |
ready: Promise<number>; | |
constructor() { | |
const { promise, resolve, reject } = defer<number>(); | |
this.ready = promise; | |
const num = Math.floor(1000 * Math.random()); | |
setTimeout(resolve, 1000, num); | |
} | |
} | |
class Consumer { | |
constructor(public name: string, public prod: Producer) { | |
this.prod.ready.then((num: number) => { | |
console.log(`${this.name} got ${num}`); | |
}) | |
} | |
} | |
console.log('START'); | |
const prod = new Producer(); | |
const consumer1 = new Consumer("consumer 1", prod); | |
const consumer2 = new Consumer("consumer 2", prod); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment