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

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Incredible Demos

  • By
    prefers-color-scheme: CSS Media Query

    One device and app feature I've come to appreciate is the ability to change between light and dark modes. If you've ever done late night coding or reading, you know how amazing a dark theme can be for preventing eye strain and the headaches that result.

  • By
    New MooTools Plugin:  ElementFilter

    My new MooTools plugin, ElementFilter, provides a great way for you to allow users to search through the text of any mix of elements. Simply provide a text input box and ElementFilter does the rest of the work. The XHTML I've used a list for this example...

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!