Last active
October 24, 2020 07:17
-
-
Save tejacques/0745b445cf0bca3c4462 to your computer and use it in GitHub Desktop.
Async Polyfill for javascript using eval and async function transform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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