JavaScript promises, mastering the asynchronous

Magus
8,491 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Let's do a harder exercise. In this code, your function receives a parameter data. You must modify the code below based on the following rules:

  • Your function must always return a promise
  • If data is not a number, return a promise rejected instantly and give the data "error" (in a string)
  • If data is an odd number, return a promise resolved 1 second later and give the data "odd" (in a string)
  • If data is an even number, return a promise rejected 2 seconds later and give the data "even" (in a string)
Change the code to return a promise

Hint: When you code a function returning a promise, make sure to always return a promise. Even if you want to handle an error, just return a promise and reject it. You will have more maintenable code like this.

Hint: use isNaN(data) to check if data is not a number

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
function job(data) {
return something;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX