Skip to main content

Practice with Promises in JavaScript

Use these exercises to practice working with JavaScript Promises.

Stopwatch

Create a simple stopwatch app that starts the timer and shows the stopped time.

  • Start the stopwatch with a promise
  • End the stopwatch on a random time between 1-10 seconds
  • When the stopwatch stops, display the time it took
Stopwatch Solution
function getRandom(max) {
return Math.floor(Math.random() * Math.floor(max))
}

function stopwatch() {
// Start the stopwatch with a promise
return new Promise(function(resolve, reject) {
// End the stopwatch on a random time between 1-10 seconds
const maxTime = getRandom(10);
console.log("Max time is:", maxTime);
let time = 0;
let interval = setInterval(() => {
time++;
// Show the current time..
console.log(time);
if (time >= maxTime) {
// Resolve the promise when the time hits the max
resolve(time);
clearInterval(interval);
}
}, 1000);
});
}

stopwatch().then(function (time) {
// When the stopwatch stops, display the time it took
console.log('Time is up! ' + time + " seconds have passed!")
})

The Tortoise and the Hare

Create two animals (a tortoise and a hare) that race each other.

  • Start each animals with a separate promise
  • End each promise on a random time between 1-10 seconds
  • Display the winner (or determine if it's a tie)
  • Display the total time it took for each animal
Tortoise and the Hare Solution
// Off to the races!
function race(animal) {
// Build the random time in the scope of this function
// This insures that we get a new random length each time this is run
console.log(`${animal} has started the race!`);
const between1and10secs = Math.floor(Math.random() * 10 + 1);
// We want to return a promise...
return new Promise((resolve) => {
// ...that will resolve between 1-10 seconds
setTimeout(
() =>
resolve(
`${animal} finished in ${between1and10secs} seconds`
),
// multiply teh random value by 1000
// because setTimeout() uses milliseconds
between1and10secs * 1000
);
});
}

const tortoisePromise = race('Tortoise');
const harePromise = race('Hare');

Promise.race([tortoisePromise, harePromise])
.then((winner) => {
// the `winner` variable is assigned to whichever promise finishes first...
// it's the value that is returned via onfullfilled
// ...so we can tell the user who won.
console.log(`Winner: ${winner}\n`);
})
.catch((error) => {
// Just in case something busted, let's log it
console.error(`Error: ${error}`);
})
.finally(() => {
// Once all the promises are done, we return the times
Promise.all([tortoisePromise, harePromise]).then(
([tortoiseResult, hareResult]) => {
console.log(tortoiseResult);
console.log(hareResult);
}
);
});

Associated Lesson

Lesson Topic
📝Intro to Promises