Last active
April 7, 2020 01:08
-
-
Save heaversm/73174f0783fff97845eecc1df361dfc6 to your computer and use it in GitHub Desktop.
Common JS Tasks and Functions
This file contains hidden or 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
//basic async await | |
// this is the function we want to schedule. it's a promise. | |
const addOne = (x) => { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
console.log(`I added one! Now it's ${x + 1}.`) | |
resolve() | |
}, 2000); | |
}) | |
} | |
// we will immediately log the first one, | |
// then the addOne promise will run, taking 2 seconds | |
// then the final console.log will fire | |
async function addAsync() { | |
console.log('I have 10') | |
await addOne(10) | |
console.log(`Now I'm done!`) | |
} | |
addAsync() | |
//wait for a variable to initialize with async/await | |
asyn initVar(){ | |
console.log("waiting for variable"); | |
while(!window.hasOwnProperty("google")){ | |
await new Promise(resolve => setTimeout(resolve, 1000)); | |
} | |
console.log("variable is defined"); | |
} | |
//or fetching an api: | |
async myFunction() { | |
try { | |
const response = await fetch(`https://api.somesite.com/v1/someendpoint/?limit=10`); | |
if (!response.ok) { | |
throw Error(response.statusText); | |
} | |
const json = await response.json(); | |
this.setState({ data: json }); | |
} catch (error) { | |
console.log(error); | |
} | |
} | |
//Data URLs and Blobs: | |
function dataURLtoBlob(dataurl) { | |
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], | |
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); | |
while(n--){ | |
u8arr[n] = bstr.charCodeAt(n); | |
} | |
return new Blob([u8arr], {type:mime}); | |
} | |
//**blob to dataURL** | |
function blobToDataURL(blob, callback) { | |
let a = new FileReader(); | |
a.onload = function(e) {callback(e.target.result);} | |
a.readAsDataURL(blob); | |
} | |
//test: | |
let blob = dataURLtoBlob(sampleURL); | |
blobToDataURL(blob, function(dataurl){ | |
console.log(dataurl); | |
}); | |
//multi-level arrow function destructure: | |
{({data: {me }})=>(...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment