[Compose] Async generator, Promise + generator
function getData(d) {
setTimeout(() => {
if (typeof d === "number") {
run.next(d/2)
} else {
run.next(d)
}
}, 500)
}
function* gen() {
var x = 1 + (yield getData(10)) // x = 1 + 5
var y = 1 + (yield getData(30)) // y = 1 + 15
var answer = (yield getData("Meaning of life: " + (x + y)))
console.log(answer)
}
var run = gen()
run.next()
Async generator able to pasue the execution and fetching data from server then resume the execution.
We writ synchronous, sequential, blocking looking code, let generator to handle all the async stuff.
Async generator can be a good tool when you want to concat all the async operations but write it in sync code.
But in previous code, there is inversion of control issue. how can we truch run.next()
called only once? we don't have control over it.
Promise + generator
function getData(d) {
return new Promise((res) => {
setTimeout(() => {
console.log("resolve")
if (typeof d === "number") {
res(d/2)
} else {
res(d)
}
}, 100)
})
}
function* gen() {
var x = 1 + (yield getData(10).then((x) => run.next(x))
var y = 1 + (yield getData(30).then((x) => run.next(x))
var answer = (yield getData("Meaning of life: " + (x + y)).then((x) => run.next(x)))
console.log(answer)
}
var run = gen()
run.next()
And async..await
is a short hand syntax of it.
function getData(d) {
return new Promise((res) => {
setTimeout(() => {
console.log("resolve")
if (typeof d === "number") {
res(d/2)
} else {
res(d)
}
}, 100)
})
}
async function gen() {
var x = 1 + await getData(10)
var y = 1 + await getData(30)
var answer = await getData("Meaning of life: " + (x + y))
console.log(answer)
}
gen()