Skip to content

Instantly share code, notes, and snippets.

@matsub
Last active May 24, 2018 05:36
Show Gist options
  • Save matsub/871913771fd08ab5d156041b1057e5d1 to your computer and use it in GitHub Desktop.
Save matsub/871913771fd08ab5d156041b1057e5d1 to your computer and use it in GitHub Desktop.
Tips for playing JavaScript w/ async&await!!

This provides some tips to use async/await in JavaScriiiiptttttt.

// an asynchronous function can be awaited in an async function
async function ping() {
let response = await fetch('https://script.google.com/macros/s/AKfycbylYt_CJN0OxcsaeTDnhFT-XIrxMiVdHSVBuCZOk_rRVSQrT7bU/exec')
return response.json()
}
class C {
// instance method can be the asynchronous!
async fetch() {
return await ping()
}
}
async function f() {
c = new C()
console.log(await ping())
console.log(await c.fetch())
}
f()
// -> {msg: "pong!"}
// -> {msg: "pong!"}
const url = "https://script.google.com/macros/s/AKfycbylYt_CJN0OxcsaeTDnhFT-XIrxMiVdHSVBuCZOk_rRVSQrT7bU/exec"
// The generators also can be asynchronous...
async function* asyncGenerator (n) {
for (let i=0; i<n; i++) {
let response = await fetch(url)
yield response.json()
}
}
// check that you need to use `for await` statement to yank aync-generator
async function useAsyncGenerator () {
for await (let item of asyncGenerator(3)) {
console.log(item)
}
}
useAsyncGenerator()
class AsyncQueue {
constructor () {
this._queue = []
this._ignition = () => {}
}
enqueue (item) {
this._queue.push(item)
this._ignition()
}
async dequeue () {
if (this._queue.length > 0) {
return this._queue.shift()
} else {
return await new Promise(resolve => {
this._ignition = () => resolve(this._queue.shift())
})
}
}
}
var aq = new AsyncQueue()
async function consume (resolve) {
while (true) {
resolve(await aq.dequeue())
}
}
for (let i=0; i<5; i++) aq.enqueue(i)
consume(console.log)
// aq.enqueue(10)
// -> 10
var btn = document.querySelector("button")
function wrapEventWithAsyncFunction () {
return new Promise(resolve => {
btn.onclick = () => resolve("whoaaaaaa!!!!")
})
}
async function awaitEvent () {
let msg = await wrapEventWithAsyncFunction()
console.log("--- emitted ---")
console.log(msg)
}
awaitEvent()
// when push the button:
// -> --- emitted ---
// -> whoaaaaaa!!!!
function generatePromise(x) {
return new Promise(resolve => resolve(x))
}
async function awaitPromise () {
let msg = await generatePromise("messaaage")
console.log(msg)
}
awaitPromise()
// -> messaaage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment