Skip to content

Instantly share code, notes, and snippets.

@cheton
Last active August 3, 2018 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheton/fb2577b84261c115577bcbdc9cd7d1d5 to your computer and use it in GitHub Desktop.
Save cheton/fb2577b84261c115577bcbdc9cd7d1d5 to your computer and use it in GitHub Desktop.
Expose Cards w/ Timeout
require('babel-core/register');
require('babel-polyfill');
const timeout = (ms) => new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`Timeout exceeded: ${ms}ms`)), ms);
});
class Player {}
class AsyncAction {
constructor() {
this.isPending = true;
this.isFullfilled = false;
this.isRejected = false;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
this.promise
.then(v => {
this.isPending = false;
this.isFullfilled = true;
return v;
})
.catch(e => {
this.isPending = false;
this.isRejected = true;
});
}
}
const players = [0, 1, 2, 3].map(n => {
const player = new Player(n);
player.asyncAction = new AsyncAction();
player.exposedCards = [];
return player;
});
const main = async () => {
try {
const r = await Promise.race([
timeout(2000),
Promise.all(players.map(player => player.asyncAction.promise))
]);
} catch (e) {
console.log('Timedout:');
} finally {
for (let i = 0; i < players.length; ++i) {
const player = players[i];
const { isPending } = player.asyncAction;
const exposedCards = player.exposedCards;
console.log(`- player #[${i + 1}]: pending=${isPending}, exposedCards=${JSON.stringify(exposedCards)}`);
}
}
};
setTimeout(() => {
// Exposes cards: ['QS']
const player = players[0];
player.exposedCards = ['QS'];
player.asyncAction.resolve(player.exposedCards);
}, 1000);
setTimeout(() => {
// Exposes cards: ['AH']
const player = players[1];
player.exposedCards = ['AH'];
player.asyncAction.resolve(player.exposedCards);
}, 2500);
setTimeout(() => {
// No candidate cards
const player = players[2];
player.exposedCards = [];
player.asyncAction.resolve(player.exposedCards);
}, 0);
setTimeout(() => {
// Refuses to expose cards: ['TC']
const player = players[3];
player.exposedCards = [];
player.asyncAction.resolve(player.exposedCards);
}, 1300);
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment