Created
August 11, 2019 20:47
-
-
Save ealipio/95582b11e508b1085f5deea20b1f2778 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//========================= utils ======================================== | |
const url = n => `https://api.mathjs.org/v4/?expr=sqrt(${n})`; | |
const sumalos = arr => arr.reduce( (acc, v) => acc + v, 0); | |
const res = r => r.json(); | |
//======================================================================== | |
// get sqrt using api.mathjs | |
async function getSqrt(number) { | |
const request = await fetch(url(number)) | |
return request.json() | |
} | |
//======================================================================== | |
async function getSumSqrt(numbers = [1,4,9,16]) { | |
const n1 = await fetch( url(numbers[0]) ).then(res); | |
const n2 = await fetch( url(numbers[1]) ).then(res); | |
const n3 = await fetch( url(numbers[2]) ).then(res); | |
const n4 = await fetch( url(numbers[3]) ).then(res); | |
console.log(sumalos([n1, n2, n3, n4])); // 10 | |
} | |
//======================================================================== | |
// same feature as previous but using Promise.all (works for whatever array size) | |
async function sumSqrts(numbers = [1,4,9,16]) { | |
const myPromises = numbers.map( async (num) => await fetch(url(num)).then(res) ); | |
const myResultArray = await Promise.all(myPromises); | |
console.log(sumalos(myResultArray)) // 10 by defualt | |
} | |
getSqrt(324).then(console.log) | |
// notice that every async function will always return a promise. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment