From b460978f2597322056c39415e3f021dc56c1e3ca Mon Sep 17 00:00:00 2001 From: Samuel Mundo Date: Wed, 12 Apr 2023 14:22:43 -0600 Subject: [PATCH] JS Async Challenges --- 1-callbacks/solution.js | 41 ++++++++++++++++---- 2-promises/solution.js | 38 +++++++++++++++--- 3-async-await/solution.js | 81 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 141 insertions(+), 19 deletions(-) diff --git a/1-callbacks/solution.js b/1-callbacks/solution.js index 654e4f5..3580f62 100644 --- a/1-callbacks/solution.js +++ b/1-callbacks/solution.js @@ -33,13 +33,40 @@ node solution.js name1 name2 name3 */ function solution() { - // YOUR SOLUTION GOES HERE - - // you get your 5 names here - - // iterate the names array and validate them with the method - - // log the final result + const validateUser = require('./validate-user'); + let TestUsers=[]; + const AllowedUsers = []; + const NotAllowedUsers = []; + + // Include process module to support arguments from the console + const process = require('process'); + var args = process.argv; + if(args.length === 2){ //If there are no arguments coming , we setup a couple of test names + TestUsers=['Sam', 'Mary', 'Juan', 'Stacy','Jimmy']; + } + else{ + args.forEach((val, index) => { + if(index>1) + TestUsers.push(val); + }); + } + + const cbFn=(error,data) => { + if(error){ + NotAllowedUsers.push(error.message) + } + else{ + AllowedUsers.push(`id: ${data.id}\nname: ${data.name}`); + } + + if(AllowedUsers.length+NotAllowedUsers.length === TestUsers.length){ //Once all names have been processed we print the result + console.log('Success\n\n',AllowedUsers.join('\n\n')); + console.log('\nFailure\n\n',NotAllowedUsers.join('\n')); + } + }; + TestUsers.forEach(function(user){ + validateUser(user,cbFn) + }) } solution() diff --git a/2-promises/solution.js b/2-promises/solution.js index 5daa659..a369639 100644 --- a/2-promises/solution.js +++ b/2-promises/solution.js @@ -25,15 +25,41 @@ const id = yourRandomMethod() //third run */ function solution() { - // YOUR SOLUTION GOES HERE + const getFirstName = require('./firstnames'); + const getLastName = require('./lastnames'); + let fullName = 'Full Name: '; - // You generate your id value here + const getRandomId = () =>{ + let randomizer= Math.floor(Math.random() * 10); + let randomString = ''; + let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < 6; i++) { + randomString += characters.charAt(Math.floor(Math.random() * characters.length)); + } + if(randomizer <=3) //returns a number + return Math.floor(Math.random() * 100); + if(randomizer===4) //returns a boolean + return Math.random() < 0.5; + if(randomizer===5) //returns undefined + return undefined; + if(randomizer==6) //returns a random string + return null; + return randomString; + } - // You call the lastnames method with your id + const id = getRandomId(); + console.log(`Testing with ID: ${id}`); + getLastName(id) + .then(lastName => { + fullName+= lastName + return getFirstName(lastName) - // You call the firstname method - - // You log the fullname, or error, here + }) + .then(firstName => { + fullName += ' ' + firstName + console.log(fullName) + }) + .catch(err => console.log(err.message)) } solution() diff --git a/3-async-await/solution.js b/3-async-await/solution.js index 38e29d9..7ef6258 100644 --- a/3-async-await/solution.js +++ b/3-async-await/solution.js @@ -20,16 +20,85 @@ Example: 9. as extra challenge: add Promise.race() and Promise.any(), and try to get the idea of what happens */ -function solution() { - // YOUR SOLUTION GOES HERE +const { CLIENT_RENEG_LIMIT } = require('tls'); - // You generate your id value here +async function solution() { + const getProducts = require('./products'); + const getPrices = require('./prices'); + //Function to generate a random ID + const getId = () =>{ + return Date.now().toString().slice(-2); + } + const id = getId(); - // You use Promise.all() here + console.log(`Testing for ID: ${id}`); + const handlePromiseAll = (res) =>{ + console.log('Processing Promise ALL'); + if(typeof res[0] ==='string' ){ + console.log({id:id,product: res[0],price:res[1]}) + } + else{ + console.log({id:id,product: res[1],price:res[0]}) + } + } + + const handleAllSettled = (res) =>{ + console.log('\nProcessing ALL settled'); + if(res[0].status && res[1].status === 'fulfilled'){ + if(typeof res[0].value ==='string' ){ + console.log({id:id,product: res[0].value,price:res[1].value}) + } + else{ + console.log({id:id,product: res[1].value,price:res[0].value}) + } + } + else{ + console.log('An error has ocurred when fetching the products or prices'); + } + } + + try{ + //Creation of new promises for Products and Prices + const products = new Promise((resolve) => { + resolve(getProducts(Number(id))); + }); + const prices = new Promise((resolve) => { + resolve(getPrices(Number(id))); + }); + + //Preparing the arry of promises + const productsAndPrices=[products,prices]; + + //executing all promises at once with Promise.all and Promise.allSettled + const results =await Promise.all(productsAndPrices); + handlePromiseAll(results); + + const settled=await Promise.allSettled(productsAndPrices); + handleAllSettled(settled); + + //Extra promise race and any + console.log('\nResults for Promise Race') + Promise.race(productsAndPrices).then((value) => { + if(typeof value ==='string' ) + console.log(`Products (${value}) settled first!`) + else + console.log(`Price (${value}) settled first!`) + }); + + Promise.any(productsAndPrices).then((value) => { + if(typeof value ==='string' ) + console.log(`Products (${value}) fulfilled first!`) + else + console.log(`Price (${value}) fulfilled first!`) + }); + } + catch(error){ + console.log('An error has ocurred while fetching the products or prices'); + } + + //Promise Race - // You use Promise.allSettled() here - // Log the results, or errors, here } solution()