forked from HackYourFuture/Assignments
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathex4-diceRace.js
More file actions
40 lines (35 loc) · 1.45 KB
/
ex4-diceRace.js
File metadata and controls
40 lines (35 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/blob/main/3-UsingAPIs/Week2/README.md#exercise-4-dice-race
1. Complete the function `rollDice()` by using `.map()` on the `dice` array
to create an array of promises for use with `Promise.race()`.
2. Refactor the function `main()` using async/await and try/catch.
3. Once you got this working, you may observe that some dice continue rolling
for some undetermined time after the promise returned by `Promise.race()`
resolves. Do you know why? Add your answer as a comment to the bottom of the
file.
------------------------------------------------------------------------------*/
// ! Do not remove these lines
import { rollDie } from '../../helpers/pokerDiceRoller.js';
/** @import {DieFace} from "../../helpers/pokerDiceRoller.js" */
export async function rollDice() {
const dice = [1, 2, 3, 4, 5];
const dicePromises = dice.map((die) => rollDie(die));
const winner = await Promise.race(dicePromises);
return winner;
}
async function main() {
try {
const result = await rollDice();
console.log('Resolved!', result);
} catch (error) {
console.log('Rejected!', error.message);
}
}
if (process.env.NODE_ENV !== 'test') {
main();
}
/*
Explanation:
Some dice keep rolling because Promise.race() only stops for the first finished promise.
The other promises keep running in the background.
*/