How to Create an Async Function via “new Function”

By  on  

One thing I love about JavaScript is that there are many ways to accomplish the same task, one such example being creating functions. There are several patterns for functions; one of the last you see used is the new Function method:

/* new Function(arg1, arg2 (...), body) */
const myFunction = new Function('users', 'salary', 'return users * salary');

What if you want to use this new Function method to create an async function? You need to be a bit clever, and thanks to MDN, we have an answer:

// Shim for allowing async function creation via new Function
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;

// Usage
const fetchPage = new AsyncFunction("url", "return await fetch(url);");
fetchPage("/").then(response => { ... });

The usage of Object.getPrototypeOf(async function(){}).constructor is super clever, as a native AsyncFunction doesn't exist. I don't believe that I've ever used the new Function pattern but that doesn't mean you don't! And now you can make them asynchronous!

Recent Features

Incredible Demos

  • By
    Using MooTools For Opacity

    Although it's possible to achieve opacity using CSS, the hacks involved aren't pretty. If you're using the MooTools JavaScript library, opacity is as easy as using an element's "set" method. The following MooTools snippet takes every image with the "opacity" class and sets...

  • By
    Create a 3D Panorama Image with A-Frame

    In the five years I've been at Mozilla I've seen some awesome projects.  Some of them very popular, some of them very niche, but none of them has inspired me the way the MozVR team's work with WebVR and A-Frame project have. A-Frame is a community project...

Discussion

  1. Gustavo

    fetch() is already an async function, can you change your example?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!