Promises for asynchronous programming – Exercise
Rothenburg ob der Tauber, Germany
Hi, here an exercise that is resolved with Javascript promises.
// Eventually resolves w/ an array of coupons (array of strings)
// this function will return the resolve response like ["coupon1", "coupon3", "coupon2"]
function getCoupons() {
return new Promise((resolve) => {
setTimeout(() => resolve(['coupon1','coupon3', 'coupon2', ]), Math.random() * 10);
});
}
// Eventually resolves w/ a discount (number)
// This method will read each item of the array ["coupon1", "coupon3", "coupon2"]
async function tryCoupon(coupon = '') {
// Will return a promise
return new Promise((resolve) => {
// variable to save the discount
let discount = 0;
// Depend of the text of the item then will return
// the value of that coupon
switch(coupon) {
case 'coupon1':
discount = 80; break;
case 'coupon2':
discount = 20; break;
case 'coupon3':
discount = 30; break;
}
// Then we will return the response (Resolve) after setTimeout time
setTimeout(() => resolve(discount), Math.random() * 10);
});
}
async function getBestCoupon() {
// Wait until getCoupons is resolve
// This const will have the data ["coupon1", "coupon3", "coupon2"]
const couponsResult = await getCoupons();
// Variables to save largestDiscount and largestCoupon
let largestDiscount = 0;
let largestCoupon = '';
// Then go through every position in the resolve data
for (var i=0; i < couponsResult.length; i++) {
// Is each item in the array like -> coupon1, coupon2, coupon3
const couponEach = couponsResult[i];
// For every item in the array we will run the tryCoupon Method
// The method will return us the value of each item
// like -> 80, 30, 20
const resultEach = await tryCoupon(couponEach);
// Will comparing to get the largest coupon
if (resultEach > largestDiscount) {
largestDiscount = resultEach;
largestCoupon = couponEach
}
}
console.log('The largest coupon is -->', largestCoupon);
// Finally will return the largest coupon
return largestCoupon;
}
getBestCoupon().then(console.log)
Result:
By Cristina Rojas.