Why does ES2017 introduce async / await when ES6 already has generators?

While reading about asyncand awaitI noticed that this is almost the equivalent of generator functions. Consider this snippet from TypeScript Deep Dive :

Waiting for Async

(...)

// Not actual code. A thought experiment
async function foo() {
    try {
        var val = await getMeAPromise();
        console.log(val);
    }
    catch(err) {
        console.log('Error: ', err.message);
    }
}

(...)

JavaScript generated

You do not have to understand this, but it is quite simple if you read about generators. A function foocan simply be wrapped as follows:

const foo = wrapToReturnPromise(function* () {
    try {
        var val = yield getMeAPromise();
        console.log(val);
    }
    catch(err) {
        console.log('Error: ', err.message);
    }
});

where it wrapToReturnPromisesimply performs the function of a generator to receive generatorand then use generator.next(), if the value is equal promise, it will be then+ a catchpromise and, depending on the result, call genertor.next(result)or genertor.throw(error). What is it!

, " "? wrapToReturnPromise - , JavaScript.

: , "", "". .

+4
1

, , - :

  • , : function* yield - async function await, , Subclass.prototype = Object.create(Superclass.prototype); Subclass.prototype.constructor = Subclass class Subclass extends Superclass

  • . await a + await b (await a) + (await b), yield a + yield b yield (a + (yield b))

  • : async/await , ( )

  • . async/await - , , "" async/await .

ES. , .

+8

Source: https://habr.com/ru/post/1671144/


All Articles