Skip to content

Instantly share code, notes, and snippets.

@michitheonlyone
Created September 24, 2021 11:39
Show Gist options
  • Save michitheonlyone/118b699f528b591ac591f67fc0f8e937 to your computer and use it in GitHub Desktop.
Save michitheonlyone/118b699f528b591ac591f67fc0f8e937 to your computer and use it in GitHub Desktop.
JavaScript Cheatscheet
// Async arrow functions look like this:
const foo = async () => {
// do something
}
// Async arrow functions look like this for a single argument passed to it:
const foo = async evt => {
// do something with evt
}
// Async arrow functions look like this for multiple arguments passed to it:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
// The anonymous form works as well:
const foo = async function() {
// do something
}
// An async function declaration looks like this:
async function foo() {
// do something
}
// Using async function in a callback:
const foo = event.onCall(async () => {
// do something
})
// Using async method inside of a class:
async foo() {
// do something
}
async function fetchPosts() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await res.json()
return data
}
async function render() {
const posts = await fetchPosts()
console.log(posts)
const postHTML = posts.map(
(post) =>
`
<div style="border: 1px solid; padding: 10px;">
<h2>
${post.title}
</h2>
<p>
${post.body}
</p>
</div>
`
)
document.body.innerHTML = postHTML
}
render()
const posts = [
{ title: 'Post One', body: 'This is Post One' },
{ title: 'Post Two', body: 'This is Post Two' },
]
function getPosts() {
setTimeout(() => {
let output = ''
posts.forEach((post) => {
output += `<li>${post.title}</li>`
})
document.body.innerHTML = output
}, 1000)
}
function createPost(post, callback) {
setTimeout(() => {
posts.push(post)
callback()
}, 2000)
}
createPost(
{
title: 'Post Three',
body: 'This is Post Tree',
},
getPosts
)
const posts = [
{ title: 'Post One', body: 'This is Post One' },
{ title: 'Post Two', body: 'This is Post Two' },
]
function getPosts() {
setTimeout(() => {
let output = ''
posts.forEach((post) => {
output += `<li>${post.title}</li>`
})
document.body.innerHTML = output
}, 1000)
}
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post)
const error = false
if (!error) {
resolve()
} else {
reject('Error: something went wrong!')
}
}, 2000)
})
}
createPost({
title: 'Post Three',
body: 'This is Post Tree',
})
.then(getPosts)
.catch((err) => console.log(err))
// async / await
async function asywait() {
await createPost({ title: 'Post Four', body: 'This is Post Four' })
getPosts()
}
asywait()
@michitheonlyone
Copy link
Author

setCustomersState(customers.filter((customer) => customer.isActive === newFilter))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment