Skip to content

Instantly share code, notes, and snippets.

@ealipio
Created August 11, 2019 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ealipio/95582b11e508b1085f5deea20b1f2778 to your computer and use it in GitHub Desktop.
Save ealipio/95582b11e508b1085f5deea20b1f2778 to your computer and use it in GitHub Desktop.
//========================= 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