jskatas.org Continuously Learn JavaScript. Your Way.

Async Function: basics

async defines an asynchronous function

can be created by putting async before

a function expression
const AsyncFunction = async function () {}.constructor; const f = function() {}; assert.equal(f instanceof AsyncFunction, true);
a function declaration
const AsyncFunction = async function () {}.constructor; function f() {} assert.equal(f instanceof AsyncFunction, true);
an arrow function
const AsyncFunction = async function () {}.constructor; const f = () => {}; assert.equal(f instanceof AsyncFunction, true);
an object method
const AsyncFunction = async function () {}.constructor; const obj = {f: () => void 0}; assert.equal(obj.f instanceof AsyncFunction, true);

the return value

is always a Promise
const f = 'nΓΆ'; assert.equal(f() instanceof Promise, true);
wraps the return value in a Promise
const f = () => 42; return f().then(v => assert.equal(v, 42));
is a rejected Promise when the async function throws
const f = async () => 0; return f() .then(() => assert(false, 'Promise must reject (not pass)!')) .catch(v => assert.equal(v, 23)) ;

Links

A short description of async function.
The actual chapter about `async`, you need to dive in from here.

Related Katas

function API

Arrow functions

Async Function

  • basics

Difficulty Level

INTERMEDIATE

First Published

9 June 2017

Stats

7 tests to solve