What is going to be the output about this javascript snippet?

Will the Now be printed before of after the After?

(If you are not familiar with await and async, you might need to read about it: async and await.)

async function sleep(ms = 0) {
      return new Promise(r => setTimeout(r, ms));
}

async function run() {
      console.log("Before: " + (new Date()).toString());
      await sleep(3000);
      console.log("After:  " + (new Date()).toString());
}

run();
console.log("Now:  " + (new Date()).toString());

It’s a bit confusing because this piece of code look like a synchronous code: no callback appears in the code. But in fact, it is asynchronous.

Order of message is tough - like one smart guy put it on twitter:

Now, let’s run the code and check if you got it right:


async function sleep(ms = 0) {
      return new Promise(r => setTimeout(r, ms));
}

async function run() {
      console.log("Before: " + (new Date()).toString());
      await sleep(3000);
      console.log("After:  " + (new Date()).toString());
}

run();
console.log("Now:  " + (new Date()).toString());

Have you git it right?

async and await are part of EcmaScript 2017 and are supported only in Chrome 55, Firefox 52.0 and Opera 42.

They are supposed to make our javascript code much more readable and our coding experience more fun.

Even if you are currently in a different browser, the above code snippet runs fine because it is transpiled with Babel Standalone.

Go ahead, play with this code snippet, modify it as you wish and it will be reevaluated after 3 seconds of inactivity (or by pressing Ctrl-Enter).

This interactive code snippet is powered by a tool of mine: the klipse plugin. If you like it, I’d really appreciate your star on github.