In this article, let us create a Javascript program that will first add all the numbers within an array and then divide the sum of all those numbers with the largest number in that array. This program will use the JavasScript Promise object which will be returned every time a function has been called to perform a task!
The first part of the program is to create the main function which will return the first promise object which will then return the resolved object which contains the sum of all the numbers as well as the largest number in the array if the condition has been met.
function add(arr) { return new Promise((resolve, reject) => { if(arr.length == 0) reject("The array is empty!") else { let sum = 0 let seed = 0 for(let i = 0; i < arr.length; i++) { sum+=arr[i] if(seed < arr[i]) seed = arr[i] } resolve({sum:sum, seed:seed}) } }) }
As you can see if the array is not empty then the Promise object will return the resolved object and passed it into the second function through its then function.
The second function will divide the sum with the largest number within that array and return the promise object which then will pass the result as the resolved object into the next function inside its then function if the non-zero condition has been fulfilled.
function divide(obj) { return new Promise((resolve, reject) => { if(obj.seed == 0) reject("Can't divide by 0!") else { resolve(obj.sum/obj.seed) } }) }
Now let us try the above programs out with the below array…
add([3,9,6]).then(c=>{return divide(c)}).then(a=>{console.log(a)}).catch(c=>{console.log(c)})
The outcome is 2 because 3+9+6=18, 18/9=2.
Now let us try to create an error in the first function by passing an empty array…
add([]).then(c=>{return divide(c)}).then(a=>{console.log(a)}).catch(c=>{console.log(c)}) // The array is empty!
Finally, let us pass in the array with all 0s…
add([0,0,0]).then(c=>{return divide(c)}).then(a=>{console.log(a)}).catch(c=>{console.log(c)}) // Can't divide by 0!
The catch method of the Promise object will display the rejecting object which is the error message of either from the first or the second promise object.
The promise object has shortened all the JavScript codes above as the program will become longer without the use of the promise object.