JavaScript exercises - Promises

This collection of 41 exercises is to practice promises, a concept that is quite tricky at first. But it is the daily diet of profesionnal JavaScript web developers. Here are some exercises to help get fit at promises.

Bite-sized, tested and vetted exercises only: no storytelling, no riddle, minimal use of math (basic arithmetic).

Promises 01

const promisedNumber = () => {
  return new Promise((resolve, reject) => {
    const randomNumber = Math.floor(Math.random() * 10);
    if (randomNumber <= 4) {
      resolve(`Valid number (${randomNumber})`);
    } else {
      reject(`Invalid number (${randomNumber})`);
    }
  });
};

Create a function sweetPromisedNumber that is the exact equivalent of the function promisedNumber but with the syntactic sugar keywords async/await. Your function should look like this:

const sweetPromisedNumber = async () => {
};

To see the solution, enter a valid code or purchase one:


Promises 02

const animals = ['Dog', 'Cat', 'Mouse', 'Flamingo'];

const randomAnimal = () => {
  return new Promise((resolve, reject) => {
    const randomIndex = Math.floor(Math.random() * animals.length);
    setTimeout(() => resolve(animals[randomIndex]), 500);
  });
};

const double = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + ' ' + text), 500);
  });
};

const capitalize = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text.toUpperCase()), 500);
  });
};

const punctuate = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + '!'), 500);
  });
};

const transformAnimal = () => {
  randomAnimal()
    .then(value => double(value))
    .then(value => capitalize(value))
    .then(value => punctuate(value))
    .then(value => console.log(value));
};

transformAnimal();

Create a function sweetTransformAnimal that is the exact equivalent of the function transformAnimal but with the syntactic sugar keywords async/await. Your function should look like this:

const sweetTransformAnimal = async () => {
};

To see the solution, enter a valid code or purchase one:


Promises 03

const animals = ['Dog', 'Cat', 'Mouse', 'Flamingo'];

const randomAnimal = () => {
  return new Promise((resolve, reject) => {
    const randomIndex = Math.floor(Math.random() * animals.length);
    setTimeout(() => resolve(animals[randomIndex]), 500);
  });
};

const double = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + ' ' + text), 500);
  });
};

const capitalize = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text.toUpperCase()), 500);
  });
};

const punctuate = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + '!'), 500);
  });
};

const sweetTransformAnimal = async () => {
  let animal = await randomAnimal();
  let doubled = await double(animal);
  let capitalized = await capitalize(doubled);
  let punctuated = await punctuate(capitalized);
  console.log(punctuated);
};

sweetTransformAnimal();

Create a function transformAnimal that is the exact equivalent of the function transformAnimal but without the syntactic sugar keywords async/await. Your function should look like this:

const transformAnimal = () => {
};

To see the solution, enter a valid code or purchase one:


Promises 04

const ANIMAL = 'Flamingo';

const delayedAnimal = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(ANIMAL), 500);
  });
};

const double = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + ' ' + text), 500);
  });
};

const capitalize = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text.toUpperCase()), 500);
  });
};

const punctuate = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + '!'), 500);
  });
};

const transformAnimal = () => {
  let transformed = delayedAnimal()
    .then(value => double(value))
    .then(value => capitalize(value))
    .then(value => punctuate(value));
  return transformed;
};

const sweetTransformAnimal = async () => {
  let animal = await delayedAnimal();
  let doubled = await double(animal);
  let capitalized = await capitalize(doubled);
  let punctuated = await punctuate(capitalized);
  return punctuated;
};

let result_1 = transformAnimal();
console.log(result_1);

let result_2 = sweetTransformAnimal();
console.log(result_2);

What does the previous code displays to the screen?

To see the solution, enter a valid code or purchase one:


Promises 05

const ANIMAL = 'Flamingo';

const delayedAnimal = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(ANIMAL), 500);
  });
};

const double = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + ' ' + text), 500);
  });
};

const capitalize = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text.toUpperCase()), 500);
  });
};

const punctuate = text => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(text + '!'), 500);
  });
};

const transformAnimal = () => {
  delayedAnimal()
    .then(value => { 
      double(value)
    })
    .then(value => {
      capitalize(value)
    })
    .then(value => {
      punctuate(value)
    })
    .then(value => {
      console.log(value);
    });
};

transformAnimal();

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Promises 06

const strange = (value) => {
  return new Promise((b, a) => {
    if (!value) {
      a(5);
    }
    b(10);
  })
};

strange(false)
  .catch((error) => console.log(error));

What does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 07

let destiny = state => {
  return new Promise(function(resolve, reject) {
    if (state) { 
      resolve('success'); 
    } else { 
      reject('error');
    }
  });
}

let sureThing = destiny(true);

sureThing
  .then(data => {  
    console.log(data + " 1");
    return destiny(true);
  })
  .then(data => {
    console.log(data + " 2");
    return 'surprise';
  })
  .then(data => {
    console.log(data + " 3");
    return false;
  })
  .then(data => {
    console.log(data + " 4");
  })
  .then(data => {
    console.log(data + " 5");
  });

What does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 08

let onFulfill = value => { console.log('onFullfill: ' + value) };
let onReject = reason => { console.log('onReject: ' + reason) };
  
const promise = new Promise((resolve, reject) => {
  if (false) {
    resolve('success value');
  } else {
    reject('nope');
  }
});
  
promise.then(onReject, onFulfill);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Promises 09

const example = new Promise( ? ? ? );

How many arguments does a Promise() constructor take?

To see the solution, enter a valid code or purchase one:


Promises 10

const asyncHello = new Promise((resolve, reject) => { 
  setTimeout(
    () => resolve('Wah gwan!'),
    1000
  ); 
}); 

console.log(typeof asyncHello);

What does the previous code display to the screen?

To see the solution, enter a valid code or purchase one:


Promises 11

Write a function resolveWithValue() that has two parameters:

  • The first parameter is a function that returns a promise.
  • The second parameter is a string value.

When called, resolveWithValue() should invoke the function argument (the first parameter) with the string argument (the second parameter) and then prints to the screen the resultant promise's resolve value or the reason for the rejection.

Here is an example of how the function resolveWithValue() can be used with the function promiseFunc(), which is a function that returns a promise.

// promiseFunc() takes in a string and returns a promise
let promiseFunc = (str) => {
  if (Math.random() < .5){
    return Promise.resolve(`Resolved with: ${str}`)
  } else {
    return Promise.reject(`Rejected with: ${str}`)
  }
}

resolveWithValue(promiseFunc, 'This exercise is done!');

To see the solution, enter a valid code or purchase one:


Promises 12

async function threePromises() {
  let first = await firstPromise();
  let second = await secondPromise(); 
  let third = await thirdPromise();
  console.log(first, second, third);
}

The previous code is not optimized, since the 3 Promises are independent. Optimize the code to make it faster to execute.

To see the solution, enter a valid code or purchase one:


Promises 13

const p1 = new Promise((_, reject) => {
  setTimeout(
      () => reject('p1 rejected'),
      1000
  );
});

const p2 = new Promise((resolve) => {
  setTimeout(
      () => resolve('p2 fulfilled'),
      2000
  );
});

const p3 = new Promise((resolve) => {
  setTimeout(
      () => resolve('p3 fulfilled'),
      3000
  );
});

Promise.all([p1, p2, p3])
  .then((result) => console.log('Success!', result))
  .catch((result) => console.log('Failure!!', result));

What does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 14

const p1 = new Promise((resolve) => {
  setTimeout(
      () => resolve('p1 fulfilled'),
      1000
  );
});

const p2 = new Promise((resolve) => {
  setTimeout(
      () => resolve('p2 fulfilled'),
      2000
  );
});

const p3 = new Promise((_, reject) => {
  setTimeout(
      () => reject('p3 rejected'),
      3000
  );
});

Promise.all([p1, p2, p3])
  .then((result) => console.log('Success!', result))
  .catch((result) => console.log('Failure!!', result));

What does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 15

const p1 = new Promise((_, reject) => {
  setTimeout(
      () => reject('p1 rejected'),
      1000
  );
});

const p2 = new Promise((resolve) => {
  setTimeout(
      () => resolve('p2 fulfilled'),
      2000
  );
});

const p3 = new Promise((resolve) => {
  setTimeout(
      () => resolve('p3 fulfilled'),
      3000
  );
});

Promise.allSettled([p1, p2, p3])
  .then((result) => console.log('Success!', result))
  .catch((result) => console.log('Failure!!', result));

What does the previous code print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 16

const p1 = new Promise((resolve, reject) => {
  resolve(1);
  console.log(2);
  reject(3);
  console.log(4);
  throw 5;
});

p1
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 17

const p2 = new Promise((resolve, reject) => {
  reject(1);
  console.log(2);
  resolve(3);
  console.log(4);
  return null;
});

p2
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 18

const p3 = new Promise((resolve, reject) => {
  console.log(1);
  return resolve(2);
  reject(3)
  console.log(4);
});

p3
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 19

const p4 = new Promise((resolve, reject) => {
  console.log(1);
  throw resolve(2);
  reject(3)
  console.log(4);
});

p4
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 20

const p11 = new Promise((resolve, reject) => {
  console.log(1);
  resolve(2);
  console.log(3);
  reject(4);
});

p11
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 21

const p12 = new Promise((reject, resolve) => {
  reject('Crocodile');
  resolve('Fish');
  return resolve('Dolphin');
});

p12
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 22

const p5 = new Promise((resolve, reject) => {
  console.log(1);
  return new Error(2);
  reject(3);
  console.log(4);
});

p5
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 23

const p6 = new Promise((resolve, reject) => {
  console.log(1);
  return null;
  reject(3);
  console.log(4);
});

p6
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 24

const p8 = new Promise((resolve, reject) => {
  console.log(1);
  return 2;
});

p8
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 25

const p7 = new Promise((resolve, reject) => {
  console.log(1);
  throw 2;
  reject(3);
  console.log(4);
});

p7
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 26

const p10 = new Promise((resolve, reject) => {
  console.log(1);
  throw 2;
});

p10
  .then((res) => console.log(`Fullfilled with value: ${res}`))
  .catch((res) => console.log(`Rejected with reason: ${res}`));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 27

const promise = setTimeout(() => Promise.resolve(2), 10);

promise
  .then((result) => console.log(result));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 28

Promise.resolve(1)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      return number + 2;
  })
  .then((number) => {
      console.log(number + 3);
  })
  .catch((number) => {
      console.log(number + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 29

Promise.resolve(2)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      return new Error(number + 2);
  })
  .then((error) => {
      console.log(error.message + 3);
  })
  .catch((error) => {
      console.log(error.message + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 30

Promise.resolve(3)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      throw number + 2;
  })
  .then((number) => {
      console.log(number + 3);
  })
  .catch((number) => {
      console.log(number + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 31

Promise.resolve(4)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      throw new Error(number + 2);
  })
  .then((error) => {
      console.log(error.message + 3);
  })
  .catch((error) => {
      console.log(error.message + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 32

Promise.resolve(5)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      return Promise.reject(number + 2);
  })
  .then((number) => {
      console.log(number + 3);
  })
  .catch((number) => {
      console.log(number + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 33

Promise.resolve(6)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      throw Promise.reject(number + 2);
  })
  .then((number) => {
      console.log(number + 3);
  })
  .catch((number) => {
      console.log(number + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 34

Promise.resolve(7)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      return Promise.resolve(number + 2);
  })
  .then((number) => {
      console.log(number + 3);
  })
  .catch((number) => {
      console.log(number + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 35

Promise.resolve(8)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      throw Promise.resolve(number + 2);
  })
  .then((number) => {
      console.log(number + 3);
  })
  .catch((number) => {
      console.log(number + 4);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 36

Promise.resolve(1)
  .then((number) => {
      return number + 1;
  })
  .then((number) => {
      throw new Error(number + 2);
  })
  .catch((value) => {
      throw value;
  })
  .then(() => {
      console.log('Failure');
  }, () => {
      console.log('Success');
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 37

Promise.resolve(1)
  .then((number) => {
      return number * 2;
  })
  .then((number) => {
      return Promise.reject(number * 2);
  })
  .then((number) => {
      return Promise.reject(number + 2);
  }, (number) => {
      return Promise.resolve(number + 3);
  })
  .catch((number) => {
      console.log(number * 2);
  })
  .then((number) => {
      console.log(number * 2); // 14
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 38

Promise.resolve(2)
  .then((number) => {
      return number * 2;
  })
  .then((number) => {
      return Promise.resolve(number * 2);
  })
  .then((number) => {
      return Promise.reject(number + 2);
  }, (number) => {
      return Promise.resolve(number + 3);
  })
  .catch((number) => {
      Promise.resolve(number + 1)
  })
  .then((number) => {
      console.log(number);
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 39

Promise.resolve(3)
  .then(() => {
    setTimeout(
      () => Promise.reject()
        .catch(() => console.log(1)),
    5
    );
    throw 2;
  })
  .then((num) => console.log(num + 1))
  .catch((num) => console.log(num + 2));

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one:


Promises 40

const mainPromise = () => {
  return new Promise((resolve, reject) => {
      console.log(1);
      return secondaryPromise()
          .then(() => {
              console.log(3);
              resolve();
          })
          .then(() => {
              console.log(4);
          })
          .then(() => {
            console.log(5);
        });
  })
};

const secondaryPromise = () => {
  return new Promise((resolve) => {
      console.log(2);
      resolve();
  });
}

mainPromise()
  .then(() => {
      console.log(6);
  })
  .catch(() => {
      console.log(7);
  });

To see the solution, enter a valid code or purchase one:


Promises 41

Promise.resolve(1)
  .then((num)=> {
      Promise.reject(2)
  })
  .catch((num) => {
      console.log(num);
  })
  .then(() => {
      console.log('Sun is shining'); 
  });

Without running the previous code, what does it print to the screen?

To see the solution, enter a valid code or purchase one: