Difference between async/await and ES6 yield with generators

前端 未结 6 780
一个人的身影
一个人的身影 2021-01-30 00:03

I was just reading this fantastic article «Generators» and it clearly highlights this function, which is a helper function for handling generator functions:



        
6条回答
  •  遥遥无期
    2021-01-30 00:34

    Well, it turns out that there is a very close relationship between async/await and generators. And I believe async/await will always be built on generators. If you look at the way Babel transpiles async/await:

    Babel takes this:

    this.it('is a test', async function () {
    
        const foo = await 3;
        const bar = await new Promise(resolve => resolve('7'));
        const baz = bar * foo;
        console.log(baz);
    
    });
    

    and turns it into this

    function _asyncToGenerator(fn) {
        return function () {
            var gen = fn.apply(this, arguments);
            return new Promise(function (resolve, reject) {
                function step(key, arg) {
                    try {
                        var info = gen[key](arg);
                        var value = info.value;
                    } catch (error) {
                        reject(error);
                        return;
                    }
                    if (info.done) {
                        resolve(value);
                    } else {
                        return Promise.resolve(value).then(function (value) {
                            return step("next", value);
                        }, function (err) {
                            return step("throw", err);
                        });
                    }
                }
    
                return step("next");
            });
        };
    }
    
    
    this.it('is a test', _asyncToGenerator(function* () {   // << now it's a generator
    
        const foo = yield 3;    //  <<< now it's yield, not await
        const bar = yield new Promise(resolve => resolve(7));
        const baz = bar * foo;
        console.log(baz);
    
    }));
    

    you do the math.

    This makes it look like the async keyword is just that wrapper function, but if that's the case then await just gets turned into yield, there will probably be a bit more to the picture later on when they become native.

    You can see more of an explanation for this here: https://www.promisejs.org/generators/

提交回复
热议问题