Console Learner — An interactive JavaScript course.


5.4 Async & Await

>>>
async function foo() {
    return 'foo';
}

  
The async function or async () => (arrow function) syntax modifies the semantics for a function.
>>>
foo()
Promise(status="fulfilled", result="foo")
Behind the scenes, an async function always returns a Promise.
>>>
await foo()
"foo"
Using await val the execution stops until the promise has been resolved or rejected.
>>>
async function bar() {
    throw new Error('bar');
}

  
Inside an async function, return and throw are automatically converted to a corresponding Promise.resolve() or Promise.reject() statement.
>>>
async function baz() {
    try {
        await foo();
        await bar();
        return '\u{1f389}';
    } catch (e) {
        return '\u{1f44e} ' + e;
    }
}

  
The resulting code therefore looks eerily similar to any synchronous code.
>>>
await baz()
"👎 Error: bar"
As long as await is not omitted, everything works as expected. And we'll never have to create a Promise again!
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.