How JavaScript Async/Await Works Under the Hood

In this article we disscuss about How JavaScript Async/Await Works Under the Hood.

How JavaScript Async/Await Works Under the Hood

The web is asynchronous in nature. User interfaces wait for user inputs. Servers wait for network requests. Databases wait for queries and mutations. The JavaScript language understands this, providing Promises in the ES6 specification to simplify asynchronous programming. Even more exciting is Async/Await coming to ES8 that further streamlines the behavior of using Promises.

For example, the Fetch API provides an interface for making network requests, returning Promises for us to resolve. To use it to get the current weather in Long Beach, we chain together two then callbacks:

In the first, we create a callback function to receive the Response object and return back its JSON data. In the second, we create a callback that receives that data and then logs it to the console.

How JavaScript Async/Await Works Under the Hood

By wrapping the logic inside an async function, we can replace the then callbacks with await statements. The effect, the code pauses execution on those lines until the Promises resolve! Asynchronous programming becomes synchronous!

Async/Await is just syntactic sugar. In this article, we will examine how it all works under the hood. To do that, we will attempt to recreate the async function from scratch!

Async Function

The key insight is to use Generators. Ultimately, we want to create an async function that takes in a generator. That way, we can nest yield statements.

Doesn’t this look uncannily like the await statements in getWeather()? In fact, await statements are just yield statements under the hood!

Thus, we need our async “polyfill” to instantiate the generator, recursively nesting next for each yield statement inside its Promise’s then callback until done is true. In other words, when each Promise resolves, its value will be passed as an argument to next, whereby g.next will replace its corresponding yield statement with that value.

HTML

<div id="mocha"></div>

JavaScript

const async = generator => {
  const g = generator();
  (function next(value) {
    const n = g.next(value);
    // console.log(n);
    if (n.done) return;
    n.value.then(next);
  })();
};

async(function*() {
  const response = yield fetch(
    "https://api.openweathermap.org/data/2.5/weather?zip=90813&APPID=5dd3e57156e6ebba767abb71509b53a0"
  );
  const data = yield response.json();
  console.log(data);
});

mocha.setup("bdd");
const { assert } = chai;

describe("Async/Await", () => {
  it("Please see console!", () => {
    assert.ok(true);
  });
});

mocha.run();

Async/Await enables us to write asynchronous code in a synchronous fashion, which produces cleaner and easier-to-understand logic. Under the hood, it’s just syntactic sugar using generators and yield statements to “pause” execution. In other words, async functions can “pull out” the value of a Promise even though it’s nested inside a callback function, giving us the ability to assign it to a variable!

Also Check out Cannot Read Property addEventListener of Null

If you interested in Entertainment genre please check this also thebiographys.com

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *