JavaScript await was rogue rogue along

https://news.ycombinator.com/rss Hits: 1
Summary

Don’t tell me you don’t know await is rogue too, jess christ. Tell me what is going here. (async () => { const x = await { then: (f) => f(4 + 2) }; console.log(x); })(); Example by Thomas Right there is a thenable, a big time Javascript interface implemented in .then callback chaining. Or as MKRhere like to put it “An object that exposes a then method is a Thenable” Now let’s explore some more interesting things. Let’s quickly reiterate on a fundamental definition. A Thenable is simply an object with a .then() method. That’s it. No fancy constructors, no new Promise(), no specific internal slots. Just a method named then. Think about it, the Promise specification itself relies heavily on the then method. It’s the core of how asynchronous operations are chained and resolved. And await, bless its rogue little heart, just says, “Hey, if you’ve got a then method that behaves like a then method, I’m good. I’ll wait for whatever value you pass to that function.” that’s incredibly pragmatic in my opinion. Now, if we internalize this, what else becomes possible? What if we don’t even need a Promise at all to await something? Thomas’s example with f => f(4 + 2) is simple enough. But what if the “value” isn’t immediately available? What if it’s… delayed? Imagine we’ve got a function that simulates fetching a user’s profile, but instead of returning a Promise, it returns a plain object that just looks like a promise. Scenario 1: The ‘Fake Promise’ that’s totally legit to await const fetchUserProfileThenable = (userId) => { console.log(`Fetching user ${userId}...`); return { then: (resolve) => { setTimeout(() => { const user = { id: userId, name: `User ${userId}'s Profile`, status: "active", }; console.log(`User ${userId} fetched!`); resolve(user); }, 1000); }, }; }; (async () => { console.log("Application starting."); const user1 = await fetchUserProfileThenable(1); console.log("Awaited user 1:", user1); const user2 = await fetchUserProfileThenable(2); console.log("Awaited use...

First seen: 2025-06-10 05:21

Last seen: 2025-06-10 05:21