请你手动实现一下 async 和 await

请你手动实现一下 async 和 await

它是一个语法糖,解决了 Promise 代码上的冗余

不过 async 标记的函数,其返回值一定是 Promise,具有一定的传染性,所以 async/await 虽好,可不要贪杯哦~

既然它能实现等一等的功能,那么它就是在生成器的基础是实现的

async 和 await 主要就是来发请求嘛,所以我搭了一个简易后台

const http = require('http')
http.createServer((req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*')
    if (req.url === '/res1') {
        res.end(JSON.stringify({
            name: 'jack',
            age: 18
        }))
    } else if (req.url === '/res2?name=jack') {
        res.end('jackInfo')
    } else if (req.url === '/res3?msg=jackInfo') {
        res.end('aaaaa')
    }
}).listen(9999)
//请求头这样设置,可以解决跨域问题

主要代码在这

function* asd(generator) {
    let iterator = generator()

    function handler(result) {
        if (result.done) {
            return
        }
        if (result.value instanceof Promise) {
            result.value.then(value => {
                handler(iterator.next(value.data))
            })
        }
    }

    handler(iterator.next())
}

let iterator = asd(function* () {
    let res1 = yield axios.get('http://localhost:9999/res1')
    console.log(res1);
    let res2 = yield axios.get('http://localhost:9999/res2?name=' + res1.name)
    console.log(res2);
    let res3 = yield axios.get('http://localhost:9999/res3?msg=' + res2)
    console.log(res3);
});
iterator.next()

/*
* 首先看效果,我们可以发现,利用yield也实现了await的功能,所以这个例子是可以的
* 利用迭代结果中的done属性,来判断是否进行下一步
* 利用Promise的成功回调,去进行下一步迭代,否则抛出异常,Promise可以直接捕获异常的不过我这里没写
* */

如果你对生成器函数还不太了解的话,请看下面:

function * gen(){
    console.log(111);
    let one = yield 'hello'
    console.log(one);
    yield 'world'
}
let iterator = gen()
console.log(iterator.next());
iterator.next('aaa')
//有规定:第二个next中传的参数将作为第一个yield的返回值
//万万注意,yield后面的不是返回值,它只是value,它本身是没有返回值的,只有在你往next里面传了参数,它才有返回值
//输出结果如下:
// 111
// { value: 'hello', done: false }
// aaa

详情请看:https://www.bilibili.com/video/BV1KF411p7Q3?share_source=copy_web

posted @ 2022-06-28 15:45  朱在春  阅读(74)  评论(0编辑  收藏  举报