JavaScript Trick Lets Non-Async Functions Silently Pass Promises Without TypeScript Knowing
A developer has demonstrated a four-line JavaScript function, MaybePromise, that can transparently handle both synchronous values and Promises without using async or await keywords. The function exploits the fact that await is only an operator inside explicitly marked async functions, meaning a Promise passed through a plain function as an opaque argument is never intercepted or wrapped by the engine. The only conditional check used is against undefined, which serves as the sole sentinel for a deferred value, while every other falsy value is treated as a present, synchronous result. The function was tested across 80 scenarios covering all major value types and usage patterns, passing every case across four variants. When placed in a TypeScript file with strict mode enabled, the function triggers implicit-any warnings, highlighting that TypeScript's type system flags the pattern even though the JavaScript runtime executes it correctly.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in