0
0
Javascriptprogramming~20 mins

Creating promises in Javascript - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Promise Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this promise code?
Consider the following JavaScript code that creates and uses a promise. What will be printed to the console?
Javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Done'), 100);
});

promise.then(result => console.log(result));
Aundefined
BDone
CError
DPromise { <pending> }
Attempts:
2 left
💡 Hint
Remember that the promise resolves after 100 milliseconds and then calls the .then() callback.
Predict Output
intermediate
2:00remaining
What does this promise reject with?
Look at this code snippet. What will be the output when the promise is rejected?
Javascript
const promise = new Promise((resolve, reject) => {
  reject('Failed');
});

promise.catch(error => console.log(error));
AFailed
Bundefined
CError
DPromise { <rejected> }
Attempts:
2 left
💡 Hint
The reject function sends the reason to the catch handler.
Predict Output
advanced
2:00remaining
What is the output of this chained promise?
Analyze the following code. What will be printed to the console?
Javascript
new Promise((resolve, reject) => {
  resolve(5);
})
.then(value => value * 2)
.then(value => { throw new Error('Oops'); })
.catch(error => 'Caught: ' + error.message)
.then(value => console.log(value));
Aundefined
B10
CError: Oops
DCaught: Oops
Attempts:
2 left
💡 Hint
Notice the error thrown and how the catch handles it.
Predict Output
advanced
2:00remaining
What will this promise output after 1 second?
What will be printed to the console after running this code?
Javascript
function delay(ms) {
  return new Promise(resolve => setTimeout(() => resolve('Waited'), ms));
}

delay(1000).then(msg => console.log(msg));
Aundefined
BPromise { <pending> }
CWaited
DError
Attempts:
2 left
💡 Hint
The promise resolves after the given milliseconds with the string 'Waited'.
Predict Output
expert
2:00remaining
What is the output of this nested promise code?
Examine this code carefully. What will be printed to the console?
Javascript
new Promise((resolve, reject) => {
  resolve('Start');
})
.then(value => {
  return new Promise((res, rej) => {
    setTimeout(() => res(value + ' End'), 50);
  });
})
.then(result => console.log(result));
AStart End
BStart
Cundefined
DError
Attempts:
2 left
💡 Hint
The first then returns a promise that resolves after 50ms with a modified string.