今日已更新 328 条资讯 | 累计 20300 条内容
关于我们

async/await is a Generator in Disguise. Let's Build It From Scratch

Parthipan Natkunam 2026年06月07日 08:31 4 次阅读 来源:Dev.to

You write await a dozen times before lunch. Fetch a row, await it. Call a service, await that. It works, you move on, and you never have to think about what the word is doing. Then one day someone asks you to explain it. Maybe it's an interviewer."But what does await actually do?" And you open your mouth and what comes out is "it, uh, waits for the promise." Which is true, and also explains nothing. We can build async/awit mechanism from scratch using generators as a learning exercise. It requires a pause button wired to a small loop that waits on a promise and then presses play again. You already know one half of that machinery if you read the last post in this series . The other half is a trick generators have that we glossed over. Put the two together and you can build a working version of async/await yourself, by hand, and watch it behave exactly like the real thing. Let's do that. The shape of the problem Strip await down to what it has to accomplish and you get two requirements: First, a function has to be able to stop in the middle. Right at the await, freeze everything, the local variables, the spot in the loop, all of it, and hand control back to whoever called it. Normal functions can't do this. They run start to finish and that's the deal. Second, something on the outside has to wait for the promise to settle and then nudge the frozen function back to life, handing it the resolved value as if the await expression had simply evaluated to it. That's the whole job. A function that pauses, and a driver that resumes it when a promise is ready. Hold that picture, because the rest of this is just filling in those two pieces with things JavaScript already gives you. The half you've seen: pausing A generator function, the function* kind, can pause itself with yield and resume later from the exact same spot. We leaned on that hard in the CSV piece to pull rows through a pipeline one at a time. A line came in, got yielded, and the generator sat frozen until someone

本文内容来源于互联网,版权归原作者所有
查看原文