How to Create an Async Function via “new Function”
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!
It's no secret that Facebook has become a major traffic driver for all types of websites. Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly. And of course there are Facebook "Like" and "Recommend" widgets on every website. One...
How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps?
This article serves as a point-by-point...
Let's be honest...WordPress' search functionality isn't great. Let's be more honest...no search functionality is better than Google's. Luckily for us, Google provides an awesome method by which we can use their search for our own site: the Google AJAX Search API.
Honesty hour confession: file uploading within the web browser sucks. It just does. Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms. Add to those criticism the fact that we're all used to drag and drop operations...
fetch() is already an async function, can you change your example?