Skip to content

Instantly share code, notes, and snippets.

@tejacques
Last active October 24, 2020 07:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tejacques/0745b445cf0bca3c4462 to your computer and use it in GitHub Desktop.
Save tejacques/0745b445cf0bca3c4462 to your computer and use it in GitHub Desktop.
Async Polyfill for javascript using eval and async function transform
/* Idea for allowing async-style functions in vanilla JS
* This transforms a function which uses await into a function
* which returns an ES6-style promise
*
* eval has the property of running the string of javascript
* with the same closure scope chain as the method it is called
* from, which is why it is necessary to call eval on the output
* of the async function, which returns a string representing
* the transformed function.
*/
// Real ES7 Async JS function:
var asyncFunction = async function() {
var x = await somePromiseNumber;
var y = await somePromiseNumberFunction();
return x + y;
};
// Proposed Example
var asyncFunction = eval(async(function() {
var x = await(somePromiseNumber);
var y = await(somePromiseNumberFunction());
return x + y;
}));
// Becomes the equivalent of this
var asyncFunction = function() {
return new Promise(function(resolve, reject) {
somePromiseNumber.then(function(x) {
somePromiseNumberFunction().then(function(y) {
resolve(x + y);
return;
}, reject);
}, reject);
});
}
// Transformation Rules/Examples
// ----------------------------------
// this
async(function() {
});
// becomes this
function() {
return Promise.resolve();
}
// ----------------------------------
// this
async(function() {
return x;
});
// becomes this
function() {
return new Promise(function(resolve, reject) {
resolve(x);
return;
});
}
// ----------------------------------
// this
var x = await(promise)
//becomes this
promise.then(function(x) {
/* rest of function */
}, reject);
// ----------------------------------
// this
x = await(promise)
//becomes this
promise.then(function(__) {
x = __;
/* rest of function */
}, reject);
// ----------------------------------
// this
await(promise)
//becomes this
promise.then(function() {
/* rest of function */
}, reject);
// ----------------------------------
// this
return await(promise)
// ----------------------------------
//becomes this
promise.then(resolve, reject);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment