Difference between async/await and ES6 yield with generators

Viewed 58300

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

function async(makeGenerator){
  return function () {
    var generator = makeGenerator.apply(this, arguments);

    function handle(result){
      // result => { done: [Boolean], value: [Object] }
      if (result.done) return Promise.resolve(result.value);

      return Promise.resolve(result.value).then(function (res){
        return handle(generator.next(res));
      }, function (err){
        return handle(generator.throw(err));
      });
    }

    try {
      return handle(generator.next());
    } catch (ex) {
      return Promise.reject(ex);
    }
  }
}

which I hypothesize is more or less the way the async keyword is implemented with async/await. So the question is, if that is the case, then what the heck is the difference between the await keyword and the yield keyword? Does await always turn something into a promise, whereas yield makes no such guarantee? That is my best guess!

You can also see how async/await is similar to yield with generators in this article where he describes the 'spawn' function ES7 async functions.

8 Answers

tl;dr

Use async/await 99% of the time over generators. Why?

  1. async/await directly replaces the most common workflow of promise chains allowing code to be declared as if it was synchronous, dramatically simplifying it.

  2. Generators abstract the use case where you would call a series of async-operations that depend on each other and eventually will be in a "done" state. The most simple example would be paging through results that eventually return the last set but you would only call a page as needed, not immediately in succession.

  3. async/await is actually an abstraction built on top of generators to make working with promises easier.

See very in-depth Explanation of Async/Await vs. Generators

Try this test programs which I used to understand await/async with promises.

Program #1: without promises it doesn't run in sequence

function functionA() {
  console.log('functionA called');
  setTimeout(function() {
    console.log('functionA timeout called');
    return 10;
  }, 15000);

}

function functionB(valueA) {
  console.log('functionB called');
  setTimeout(function() {
    console.log('functionB timeout called = ' + valueA);
    return 20 + valueA;
  }, 10000);
}

function functionC(valueA, valueB) {

  console.log('functionC called');
  setTimeout(function() {
    console.log('functionC timeout called = ' + valueA);
    return valueA + valueB;
  }, 10000);

}

async function executeAsyncTask() {
  const valueA = await functionA();
  const valueB = await functionB(valueA);
  return functionC(valueA, valueB);
}
console.log('program started');
executeAsyncTask().then(function(response) {
  console.log('response called = ' + response);
});
console.log('program ended');

Program #2: with promises

function functionA() {
  return new Promise((resolve, reject) => {
    console.log('functionA called');
    setTimeout(function() {
      console.log('functionA timeout called');
      // return 10;
      return resolve(10);
    }, 15000);
  });
}

function functionB(valueA) {
  return new Promise((resolve, reject) => {
    console.log('functionB called');
    setTimeout(function() {
      console.log('functionB timeout called = ' + valueA);
      return resolve(20 + valueA);
    }, 10000);

  });
}

function functionC(valueA, valueB) {
  return new Promise((resolve, reject) => {
    console.log('functionC called');
    setTimeout(function() {
      console.log('functionC timeout called = ' + valueA);
      return resolve(valueA + valueB);
    }, 10000);

  });
}

async function executeAsyncTask() {
  const valueA = await functionA();
  const valueB = await functionB(valueA);
  return functionC(valueA, valueB);
}
console.log('program started');
executeAsyncTask().then(function(response) {
  console.log('response called = ' + response);
});
console.log('program ended');

In many ways, generators are a superset of async/await. Right now async/await has cleaner stack traces than co, the most popular async/await-like generator based lib. You can implement your own flavor of async/await using generators and add new features, like built-in support for yield on non-promises or building it on RxJS observables.

So, in short, generators give you more flexibility and generator-based libs generally have more features. But async/await is a core part of the language, it's standardized and won't change under you, and you don't need a library to use it. I have a blog post with more details on the difference between async/await and generators.

The yield+gen.next()-as-a-language-feature can be used to describe (or implement) the underlying control-flow that await-async has abstracted away.


As other answers suggest, await-as-a-language-feature is (or can be thought of) an implementation on top of yield.

Here is a more intutive understanding for that:

Say we have 42 awaits in an async function, await A -> await B -> ...

Deep down it is equivalent to having yield A -> tries resolve this as a Promise [1]

-> if resolvable, we yield B, and repeat [1] for B

-> if not resolveable, we throw

And so we end up with 42 yields in a generator. And in our controller we simply keep doing gen.next() until it is completed or gets rejected. (ie this is the same as using await on an async function that contains 42 await.)

This is why lib like redux-saga utilizes generator to then pipe the promises to the saga middleware to be resolved all at one place; thus decoupling the Promises constructions from their evaluations, thus sharing close resemblance to the Free Monad.

The idea is to recursively chain then() calls to replicate the behavior of await which allows one to invoke async routines in a synchronous fashion. A generator function is used to yield back control (and each value) from the callee to the caller, which happens to be the _asyncToGenerator() wrapper function.

As mentioned above, this is the trick that Babel uses to create polyfills. I slightly edited the code to make it more readable and added comments.

(async function () {
  const foo = await 3;
  const bar = await new Promise((resolve) => resolve(7));
  const baz = bar * foo;
  console.log(baz);
})();

function _asyncToGenerator(fn) {
  return function () {
    let gen = fn(); // Start the execution of the generator function and store the generator object.
    return new Promise(function (resolve, reject) {
      function step(func, arg) {
        try {
          let item = gen[func](arg); // Retrieve the function object from the property name and invoke it. Similar to eval(`gen.${func}(arg)`) but safer. If the next() method is called on the generator object, the item value by the generator function is saved and the generator resumes execution. The value passed as an argument is assigned as a result of a yield expression.
          if (item.done) {
            resolve(item.value);
            return; // The executor return value is ignored, but we need to stop the recursion here.
          }
          // The trick is that Promise.resolve() returns a promise object that is resolved with the value given as an argument. If that value is a promise object itself, then it's simply returned as is.
          return Promise.resolve(item.value).then(
            (v) => step("next", v),
            (e) => step("throw", e)
          );
        } catch (e) {
          reject(e);
          return;
        }
      }
      return step("next");
    });
  };
}

_asyncToGenerator(function* () { // <<< Now it's a generator function.
  const foo = yield 3; // <<< Now it's yield, not await.
  const bar = yield new Promise((resolve, reject) => resolve(7)); // <<< Each item is converted to a thenable object and recursively enclosed into chained then() calls.
  const baz = bar * foo;
  console.log(baz);
})();
Related