Solution Review: Even or Odd?
This lesson will explain the solution to the problem in the previous lesson.
We'll cover the following...
Solution #
Press + to interact
function evenOdd(num) {return new Promise(function(resolve,reject){if(isNaN(num)){reject("error")}if((num%2) != 0){setTimeout(function(){resolve("odd")},1000)}if(num%2 == 0){setTimeout(function(){reject("even")},2000)}});}function test(number){return evenOdd(number).then(function(result){console.log(result)}).catch(function(error){console.log(error)})}test(5)test(1)test(0)test(2)test('abc')
Explanation #
Let’s look at the evenOdd
function first.
The function takes a number num
and returns a new promise
. The callback function passed as a parameter to the promise
has two parameters: resolve()
and ...