Skip to content

Instantly share code, notes, and snippets.

@southpolesteve
Created December 6, 2019 17:16
Show Gist options
  • Save southpolesteve/381ea9e7cb94de8fcf578c6875438b22 to your computer and use it in GitHub Desktop.
Save southpolesteve/381ea9e7cb94de8fcf578c6875438b22 to your computer and use it in GitHub Desktop.
Detect forgotten "await" with JavaScript proxies
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