JavaScript Detect Async Function

Publikováno: 29.4.2019

JavaScript async/await has changed the landscape of how we code. We’re no longer stuck in callback or then hell, and our code can feel more “top down” again. Async functions require the following syntax: async function myFunction() { } To use await with a function, the function needs to be declared with async. That got […]

The post JavaScript Detect Async Function appeared first on David Walsh Blog.

Celý článek

JavaScript async/await has changed the landscape of how we code. We’re no longer stuck in callback or then hell, and our code can feel more “top down” again.

Async functions require the following syntax:

async function myFunction() {

}

To use await with a function, the function needs to be declared with async. That got me to thinking: is it possible to detect if a function is asynchronous?

To detect if a function is asynchronous, use the function’s constructor.name property:

const isAsync = myFunction.constructor.name === "AsyncFunction";

If the value is AsyncFunction, you know the function is async!

Async functions are my preferred method of working with promises. Knowing if a function is async could be useful as a library creator or a typing/validation utility.

The post JavaScript Detect Async Function appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace