Created
December 6, 2019 17:16
-
-
Save southpolesteve/381ea9e7cb94de8fcf578c6875438b22 to your computer and use it in GitHub Desktop.
Detect forgotten "await" with JavaScript proxies
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
const nativePromise = globalThis.Promise | |
globalThis.Promise = new Proxy(nativePromise, { | |
construct(...args){ | |
const promise = Reflect.construct(...args) | |
const proxy = new Proxy(promise, { | |
get: function(target, prop) { | |
const value = Reflect.get(target, prop); | |
if (prop === "then"){ | |
proxy.awaited = true | |
} | |
return typeof value == 'function' ? value.bind(target) : value; | |
} | |
}) | |
proxy.awaited = false | |
setTimeout(() => { | |
if (proxy.awaited === false){ | |
throw new Error('You forgot to await a promise') | |
} | |
}, 0) | |
return proxy | |
} | |
}) | |
async function main(){ | |
const promise1 = await Promise.resolve() | |
const promise2 = Promise.resolve() | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment