[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()

 

posted @   Zhentiw  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-10-26 [React] useEffect - problem: dependency is Object
2022-10-26 [Typescript] 70. Medium - Without
2022-10-26 [Typescript] 69. Medium - Trim Right
2022-10-26 [React] useEffect - problem: depending On State Mutated In The useEffect
2022-10-26 [RxJS] merge - build count down example
2022-10-26 [Typescript] 68. Medium - Fill
2020-10-26 [CSS] Use CSS Transforms to Create Configurable 3D Cuboids
点击右上角即可分享
微信分享提示