<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mazen Khiami on Medium]]></title>
        <description><![CDATA[Stories by Mazen Khiami on Medium]]></description>
        <link>https://medium.com/@sgaawc?source=rss-b539e3ea792d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r-0xozAZ9EAZAQOxhQ-L9Q.jpeg</url>
            <title>Stories by Mazen Khiami on Medium</title>
            <link>https://medium.com/@sgaawc?source=rss-b539e3ea792d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:51:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sgaawc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Plumber’s Guide to Node.js: Passing Context Without the Pipe-Fitting Nightmare]]></title>
            <link>https://medium.com/@sgaawc/the-plumbers-guide-to-node-js-passing-context-without-the-pipe-fitting-nightmare-01c9b5b266b7?source=rss-b539e3ea792d------2</link>
            <guid isPermaLink="false">https://medium.com/p/01c9b5b266b7</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Mazen Khiami]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 14:27:47 GMT</pubDate>
            <atom:updated>2026-07-07T14:27:47.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDzDrShXABGIsddk8YdFkw.jpeg" /></figure><h3>The Prop Drilling Nightmare</h3><p>Let’s take a collective deep breath.</p><p>This article is not about how a new LLM is going to write your code or steal your job. Instead, we are talking about a classic, daily software engineering pain: <strong>parameter plumbing</strong>.</p><p>Imagine you have a variable at the very start of a request flow (like a database transaction or a user session), and you need it at the very bottom, fifteen layers deep. Your only option is to pass it through every single function in the chain like a game of telephone.</p><pre>async function createUser(tx, userData) {<br>  const user = await saveToDb(tx, userData);<br>  await auditLog(tx, `User ${user.id} created`);<br>}<br><br>async function saveToDb(tx, userData) {<br> // tx: poor me 🤕<br>  return await db.insert(tx, &#39;users&#39;, userData);<br>}<br><br>async function auditLog(tx, message) {<br>  // tx: here once again! 🥴<br>  return await db.insert(tx, &#39;audit_logs&#39;, { message });<br>}</pre><p>Every single function signature in your system is now tightly coupled to your database driver’s transaction handle. If you change how you handle transactions, you have to rewrite fifty files.</p><p>Let’s meet AsyncLocalStorage—the native Node.js tool that saves you from this plumbing hell.</p><p><strong>**A Quick Side Note:**</strong> If AsyncLocalStorage is already your bread and butter and you could write this API in your sleep — first of all, you’re an absolute legend. Feel free to skip this read. For everyone else who is tired of passing transaction variables down 15 levels of function calls, keep going. I promise this is going to be worth your while!</p><h3>The Great Debate: Why Not Just Use a Shared Service? 🧐</h3><p>At this point, a reasonable developer might say: <em>“Why all this parameter passing? Let’s just create a shared singleton service or a global config object to hold the current transaction!”</em></p><p>It sounds simple:</p><pre>// A global shared service<br>class TransactionManager {<br>  private currentTx = null;<br>  setTx(tx) { this.currentTx = tx; }<br>  getTx() { return this.currentTx; }<br>}<br>export const txManager = new TransactionManager();</pre><p>Here is why this fails catastrophically in Node.js: <strong>concurrency</strong>.</p><p>JavaScript is single-threaded, but it handles operations concurrently via the event loop. If Request A comes in and sets the transaction in txManager, Node.js might pause Request A to wait for a database query. In that split second, Request B comes in and overwrites the transaction in the singleton. When Request A resumes and reads from the shared service, it will accidentally execute its queries under Request B&#39;s transaction context.</p><p>Shared services are excellent for stateless logic, but storing request-specific state in a global singleton is a direct ticket to production data corruption.</p><h3>The Plumber’s Toolkit: Comparing the Options</h3><p>Before we look at the native Node.js solution, let’s lay out the tools available in a developer’s toolkit to solve parameter plumbing, along with their pros and cons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tU09Fa65JLZnqz9Qdhh2bA.png" /><figcaption>Node.js Context Passing Options (Artwork generated by Nano 🍌)</figcaption></figure><p>If a global variable is too shared, and parameter passing is too tedious, AsyncLocalStorage is the professional, native way to resolve the conflict.</p><p>Think of it as an <strong>invisible portal</strong> that follows your code’s execution path. When you initialize a context, Node.js links that context to the active asynchronous call stack. No matter how many times Node pauses your execution to run other tasks, when your code resumes, Node knows exactly which context belongs to it.</p><p>Here is a visual breakdown of how Node.js leverages AsyncLocalStorage to capture and restore context across asynchronous event loop boundaries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OALOgLIywV5CIyR8SrXWA.png" /><figcaption>How AsyncLocalStorage propagates context across the Event Loop (Artwork generated by Nano 🍌 )</figcaption></figure><h3>The Use Case: Provider-Agnostic Context Transactions</h3><p>Let’s build a transaction manager that keeps our repositories clean of database-specific parameters.</p><pre>import { AsyncLocalStorage } from &quot;node:async_hooks&quot;;<br><br>// 1. Create the store<br>export const transactionStorage = new AsyncLocalStorage&lt;DatabaseTransaction | null&gt;();<br><br>// Runs a function inside a transaction block, implicitly propagating the context.<br>export async function runInTransaction&lt;T&gt;(<br>  dbClient: DatabaseClient, <br>  fn: () =&gt; Promise&lt;T&gt; | T<br>): Promise&lt;T&gt; {<br>  // 2. Start the database transaction<br>  return dbClient.runTransaction(async (tx) =&gt; {<br>    // 3. Bind the transaction to the current execution path<br><br>    // Because we need to store the &quot;tx&quot; in the store,<br>    // we need to create one first before running the als and passing it along<br>    return transactionStorage.run(tx, async () =&gt; {<br>      return await fn();<br>    });<br>  });<br>}<br><br>/**<br> * Helper to fetch the transaction from context<br> */<br>export function getTransactionFromContext() {<br>  return transactionStorage.getStore();<br>}</pre><p>Now, your database repository doesn’t need to accept a tx parameter. It just fetches it:</p><pre>class UserRepository {<br>  async update(userId: string, data: any) {<br><br>    // Our repo doesn&#39;t care anymore about how the update is executed<br>    // It&#39;s the DatabaseClient below .. kijk hieronder 👇🏻 <br>    await db.update(&#39;users&#39;, userId, data);<br>  }<br>}<br><br>class DatabaseClient {<br>  constructor(private rawClient: any) {}<br><br>  async update(collection: string, id: string, data: any) {<br>    // Check if we are running inside an active transaction context<br>    const tx = getTransactionFromContext();<br><br>    if (tx) {<br>      // Execute the query using the transaction context<br>      return await tx.update(collection, id, data);<br>    }<br>    // Fall back to a standard update<br>    return await this.rawClient.update(collection, id, data);<br>  }<br>}</pre><p>No more passing tx through every single method signature!</p><p><strong>TypeScript Pro-Tip:</strong> Since ALS.getStore() returns T | undefined, you might want to enforce context presence in critical paths. You can create a helper like getTransactionOrThrow() which throws a helpful error if someone calls a repository method outside an active transaction block.</p><h3>How to Tame the Cons of AsyncLocalStorage</h3><p>While AsyncLocalStorage is the native champion, it has a few trade-offs. Here is how you address them like a pro:</p><h4>Trade-off 1: “It feels like magic” (Implicit Context)</h4><p>Because context is fetched invisibly, it can make code harder to debug or mock in unit tests.</p><ul><li><strong>The Fix:</strong> Never use ALS for business data (like usernames or parameters). Restrict its usage to <strong>infrastructure concerns</strong> only — like database transactions, trace correlation IDs, or request-scoped logger instances, system mode flags. Wrap ALS access behind clear, explicit helpers (e.g., getTransactionFromContext()).</li><li><strong>For Testing:</strong> You can easily mock the context. In your tests, run the repository method inside a mock transaction store:</li></ul><pre>test(&quot;updates user data&quot;, async () =&gt; {<br>  const mockTx = { update: jest.fn() };<br>  await transactionStorage.run(mockTx, async () =&gt; {<br>    await userRepository.update(&quot;user-123&quot;, { name: &quot;Alice&quot; });<br>  });<br>  expect(mockTx.update).toHaveBeenCalled();<br>});</pre><h4>Trade-off 2: Loss of Context Across Boundaries</h4><p>If you pass execution to legacy callback-based libraries or custom task queues (e.g., raw EventEmitters or certain message brokers), the context connection can get cut.</p><ul><li><strong>The Fix:</strong> Use AsyncLocalStorage.bind(fn) or run to explicitly re-bind functions that cross async borders when using legacy libraries. Modern promise-based code (async/await) handles this natively without issue.</li></ul><h4>Trade-off 3: Performance Overhead</h4><p>Historically, context propagation in Node.js (async_hooks) had a noticeable performance tax.</p><ul><li><strong>The Fix:</strong> Modern versions of Node.js (v16+) have heavily optimized the V8 implementation of AsyncLocalStorage. The performance overhead is now negligible (less than a fraction of a microsecond per call)—meaning you can use it in production without second-thought optimization fears.</li></ul><h3>The “Un” Effect (Exiting the Portal)</h3><p>Sometimes, the portal is <em>too</em> sticky. If you spawn an asynchronous background task (like sending a webhook or triggering vector search embeddings) <em>inside</em> the transaction callback, it inherits the transaction context.</p><p>This leads to bugs:</p><ol><li><strong>Lock Contention:</strong> Slow API calls or background jobs hold the database transaction lock open.</li><li><strong>Transaction Violations:</strong> Your background task tries to write to a log database, but the main database driver throws an error because that table isn’t part of the transaction.</li></ol><p>We need to <strong>exit the portal</strong> temporarily. We call this the <strong>“Un” Effect</strong> (the nullified store).</p><pre>export async function runWithoutTransaction&lt;T&gt;(fn: () =&gt; Promise&lt;T&gt; | T): Promise&lt;T&gt; {<br>  // Overwrites the active transaction context with null<br>  return transactionStorage.run(null, fn);<br>}</pre><h4>Example: Post-Commit Side Effects</h4><p>When updating user data, we want to archive old logs inside a transaction, but fire off a background search-index update <em>afterwards</em> without blocking:</p><pre>async function handleUserUpdate(userId: string, data: any) {<br>  // 1. Transactional db changes<br>  await runInTransaction(db, async () =&gt; {<br>    await userRepository.update(userId, data);<br>  });<br><br>  // 2. Post-transaction background task<br>  runWithoutTransaction(async () =&gt; {<br>    // Run this outside the transaction so it doesn&#39;t hold locks<br>    await searchIndexService.updateIndex(userId).catch(console.error);<br>  });<br>}</pre><h3>Other Use cases (And Where You Already See It)</h3><p>Beyond database transactions, AsyncLocalStorage is incredibly useful for:</p><p><strong>Correlation IDs:</strong> Generate a UUID in your HTTP request middleware, store it in ALS, and print it in every log. Now, every log line related to a request shares the same trace ID.</p><p><strong>Under the Hood of Frameworks:</strong> You are probably already using this without knowing it:</p><ul><li><strong>Next.js</strong> uses it to power request-scoped APIs like cookies() and headers().</li><li><strong>NestJS</strong> uses it for managing global request scopes and transactional CLS hooks.</li><li><strong>OpenTelemetry</strong> uses it to track and correlate network tracing across microservices.</li></ul><h3>Ready to Go Deeper?</h3><p>If you’re eager to learn more about `AsyncLocalStorage` and explore the rest of its implementation, there is a lot of useful stuff to discover. Head over to the official Node.js AsyncContext <a href="https://nodejs.org/api/async_context.html">API Reference</a> to check out the details and level up your asynchronous architecture.</p><h3>The Future: TC39 AsyncContext</h3><p>Currently, AsyncLocalStorage is a Node-specific API. But the <strong>TC39 AsyncContext proposal</strong> (currently Stage 2) is working on baking this directly into JavaScript.</p><p>Once it lands, you’ll be able to run context-aware code in browsers, Edge Workers, Bun, Deno, and Node natively using AsyncContext.Variable.</p><h3>TL;DR</h3><ol><li>Put your context in the portal (ALS.run).</li><li>Fetch it deep down without parameters (ALS.getStore).</li><li>Exit the portal for background tasks (ALS.run(null, fn)).</li></ol><p>Now go forth, delete those parameters, and clean up your codebase!</p><p><em>Thanks for reading! If you enjoyed this and want to keep your Node.js plumbing leaks under control, smash that clap button, drop a comment with your worst parameter-drilling horror story, and follow along for more JavaScript wizardry. Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01c9b5b266b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clarifying Some of the Most Ambiguous Crash Reports in React-Native]]></title>
            <link>https://medium.com/quick-code/clarifying-some-of-the-most-ambiguous-crash-reports-in-react-native-25ba6bbe48f9?source=rss-b539e3ea792d------2</link>
            <guid isPermaLink="false">https://medium.com/p/25ba6bbe48f9</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[crash-reporting]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Mazen Khiami]]></dc:creator>
            <pubDate>Sat, 23 Feb 2019 11:51:05 GMT</pubDate>
            <atom:updated>2019-05-12T06:54:27.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vqh0ZoxEm1ge3XlpslFYCQ.jpeg" /><figcaption>Reference <a href="https://facebook.github.io/react-native/blog/2018/11/01/oss-roadmap">https://facebook.github.io/react-native/blog/2018/11/01/oss-roadmap</a></figcaption></figure><p>This article puts together a checklist of some of the most ambiguous crash reports in React-Native, it explains their causes and suggests the possible resolution. However, judging any aspect of the framework or evaluating the process of certain components is completely out of scope here.</p><p>The reason I chose to write this article is because of the level of frustration I had during my development of the recently shipped tablet app using React-Native. My usual duties at Fuego range from the websites development, frontend prototyping to mobile apps development. However, the latter do not often stick on my plate since the development team is equipped with the native development resources for both iOS and Android. Although, we picked the hybrid approach to meet a time crunch and launch the app on both platforms.</p><p>The fact that React-Native is a popular framework and evolves quickly put me under pressure. The last time I used RN for app development was two years ago. At that time, RN was at 0.43, a lot has changed since then, displayed bugs and errors, native module APIs, discontinued support of a couple of third-party modules, etc..</p><p>Luckily, with the latest release, my personal experience with store management and offline-first thought in mind was great. What turned bad was the moments I had to deal the crash reports that do not say much about the situation.</p><h4>The observations I documented are particularly on Android, not to say that Xcode was going entirely smooth, but the errors were at least obvious and straight to the point.</h4><p>It is unpleasant when you end up debugging errors that are irreproducible and sporadic. With an application stretched to around 25 screens and connecting ~40 web services, compiling a release that crashes before it starts without leaving any marks or logs was not a good sign. With the blocking I faced to resolve these issues, it got me thinking to share my findings with the community.</p><p>The crash reports presented below are listed based on their level of ambiguity.</p><h4><strong>1- Requested keys of a value that is not an object</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9EjPml9Lq1NL_ffFR8jHiw.png" /><figcaption>Emulator screenshot showing the crash report</figcaption></figure><p>This is the worst ever amongst the others yet trivial and simple to fix. If you keep tracking the stack, you will end up playing around with ‘<em>autoRehydrate.js</em>’ file. As that file’s name explains the problem, I started doubting redux-persist configs. Since the error was not reproducible, it was hard to debug and track back its source. I kept ignoring it until the first release was built to start internal testing, that time it turned to become a real pain. The app crashed before booting and the ‘<em>adb</em>’ logging command was completely useless because nothing was logged on the screen.</p><p>The only time this crash report is discussed by the community was about a third-party library using the AWS services, which was irrelevant to my case, so I had to isolate the entire project and start with the simplest setup of redux. What caused the issue was the misconfigured redux-offline in the store, it backfired both state persistence and rehydration process. As redux-offline recommended setup uses redux-persist v4 (older version), the decision I made was to use (the latest version) v5 to get the advantage of the new features, but I overlooked the configuration differences for the latest version.</p><p>Luckily, the <a href="https://gist.github.com/jarvisluong/f14872b9c7ed00bc2afc89c4622e3b55">new configs</a> were available in redux-offline. Make sure to install that dependency and configure it well to avoid living with this error for long. The following gist shows terminal logs when the app runs after booting on debug mode.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf582770f47d2825c6f9550b917c79ba/href">https://medium.com/media/bf582770f47d2825c6f9550b917c79ba/href</a></iframe><h4><strong>2- Debug build failed</strong></h4><p>This crash logs ‘<em>FAILURE: Build failed with an exception</em>’ in the terminal and suspends the building process for both debug and release variants. The terminal shows the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3777fb5fbd786b2c39ec22e035128ba/href">https://medium.com/media/c3777fb5fbd786b2c39ec22e035128ba/href</a></iframe><p>While for a web developer, this might not be as clear as a browser error to know what went wrong, the resolution is quite simple. The following gist shows the correct way to list down the repositories inside <strong>./android/build.gradle</strong> file (you might not necessarily have them all, but just in case ‘google()’ is listed, ensure it is on top of the list)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf8443f26af0dfbffd7e9896df8f528/href">https://medium.com/media/baf8443f26af0dfbffd7e9896df8f528/href</a></iframe><p>While this error has nothing to do with React-Native, I personally wished that Gradle (cli tool) could show a comprehensive message to stay informed. Thanks to react-native community who helped in pinpointing the issue and providing support.</p><h4><strong>3- Google services version check</strong></h4><p>Another crash report logged in the terminal when the app compiles a release variant. The more third-party libraries we use, the higher are the chances to face version compatibility issues. In this error, Gradle runs an automated version-compatibility check, and logs warnings/errors when applicable, unless that check is explicitly disabled from gradle. In order to do so, the following command needs to be added <strong>build.gradle</strong> under to <strong>./android/app/</strong> (ideally, at the very end of the file):</p><pre><em>com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1a99c0e5575e7845f0622f2eefd8c78/href">https://medium.com/media/a1a99c0e5575e7845f0622f2eefd8c78/href</a></iframe><h4><strong>4- Text strings must be rendered within a &lt;Text&gt; component</strong></h4><p>Another simple and straightforward error yet elusive to spot is when accidentally leaving a string without surrounding it by <strong><em>&lt;Text&gt;</em></strong> component. While this trivial mistake may not seem major, it can crash the app if it is overlooked and compiled for production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EWifq8hFKtuCEPLBsod6sQ.png" /><figcaption>Emulator screenshot showing the crash report</figcaption></figure><p>The titled error may seem fairly obvious. However, when the error lies in a deeply nested components, R<strong>eact-Native fails to inform the developer on the exact error location</strong>. Personally, I spent around 15 minutes, traversing desperately through the nested components to locate the defect. For that, falling victim here is quite common when using the <strong>shorthand conditional expressions</strong> while rendering. Here is a quick example to showcase that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b532dadd57e4209b972bafc039192597/href">https://medium.com/media/b532dadd57e4209b972bafc039192597/href</a></iframe><p>As you can see, using ’<em>textArray.length</em>’ as a conditional expression returns a number, and triggers the error titled above. After several trials and side experiments, my only recommendation to avoid this crash is to always convert all the conditional expressions to Boolean data type. The following gist shows the same component but after Data Type conversion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389fcdd93104cea92d0f236a8bc9f40a/href">https://medium.com/media/389fcdd93104cea92d0f236a8bc9f40a/href</a></iframe><p>Notice the function the precedes render, ‘<em>typeOf</em>’ can be a good assistant to check/assert the data-type before passing a certain object. With the above adjustments, the <em>render</em> function returns the expected results with safety coding-practice in mind.</p><h4><strong>5- Objects are not valid as React child. If you mean to render a collection of children, use an array instead.</strong></h4><p>As ugly as it seems, it was utterly unpleasant when I first came to know that React does not yet support <strong>asynchronous rendering</strong>. But not for long, as it sounds a <strong>major upgrade in the library</strong> and to the <strong>component lifecycle</strong>, the team behind React will soon roll out this feature, starting from v17.0. Apparently, the upgrade will be gradual as there are more than 50K components maintained by Facebook. Please <a href="https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html">click here</a> for more details.</p><p>In the meanwhile, the proposed approach by React is quite simple. In short, consume the async feed after the component finished loading, store the async feed in the state (‘<em>setState</em>’) that will directly trigger the ‘<em>render’</em> cycle and update the view.</p><p>The following gist shows a real use-case where I had to render the list of local notifications, scheduled as reminders on the view. The following snippet uses <a href="https://github.com/invertase/react-native-firebase">react-native-firebase</a> to generate the notifications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11e0365b2fd8e4163c6efa1dd5866901/href">https://medium.com/media/11e0365b2fd8e4163c6efa1dd5866901/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6AdDfoqtU_RO7YMLFUVf4A.png" /><figcaption>Emulator screenshot showing the crash report</figcaption></figure><p>The above crash error will show up when you attempt to convert the component render function to async/await.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88fa4b293f642789bd437251e985aa15/href">https://medium.com/media/88fa4b293f642789bd437251e985aa15/href</a></iframe><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25ba6bbe48f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quick-code/clarifying-some-of-the-most-ambiguous-crash-reports-in-react-native-25ba6bbe48f9">Clarifying Some of the Most Ambiguous Crash Reports in React-Native</a> was originally published in <a href="https://medium.com/quick-code">Quick Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fed up with Promises? Try Generator Functions.]]></title>
            <link>https://medium.com/@sgaawc/fed-up-with-promises-try-generator-functions-64b6688cf7fa?source=rss-b539e3ea792d------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b6688cf7fa</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[function-generators]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript-promise]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mazen Khiami]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 15:00:08 GMT</pubDate>
            <atom:updated>2018-10-02T15:00:08.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqQy_JxaogqqEHXk7D7ADA.jpeg" /><figcaption>Tank deals with promises in the Matrix like a boss.</figcaption></figure><p>Working with async functions can be joyful and intriguing. The journey of the async programming can continue outside the scope of the running functions. It ensures a non-blocking form of IO programming structure. It’s commonly found in the event-based program interfaces and used in many different pieces in the web e.g. CRUD operations from the browser side or request call on the server side to a third party service. However, dealing with an increasing number of async functions in a program can be quite tedious if not being handled well.</p><p>Promises, as we know, can resolve or reject the result and pass the error if caught by the catch function. All of these add extra scopes to the already curated function to handle a desired result. Each of which can create a new callback function, depending on the workflow of the program, e.g. a script may ignore a certain error or be just logged into the log module.</p><p>In this article, we will take a look at four different ways to deal with promises, they all meet the exact same purpose but are different in terms of script <strong>maintainability</strong>, <strong>legibility</strong> and <strong>ease of setup</strong>. Finally, concluding with the easiest, efficient and effective approach.</p><blockquote>I, personally, used them all in one point in time but started shifting towards the advanced and more maintainable approach to make my life easier while scripting and to give time to critically think about the overall solution, workflow, etc..</blockquote><p>All examples will be running using <em>Node.js</em> for, and for the sake of demoing the results, <a href="https://www.npmjs.com/package/express"><em>Express.js</em></a> module will be included to show the results as a web service call which might be part of real life scenario.</p><p>The following example is just for documentation and comparison purposes. Jump right to the end of the article if you don’t want to bother with these basic stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FIYKr-SeGHMlOQHiE62HQ.jpeg" /><figcaption>image source: <a href="https://eng.localytics.com/better-asynchronous-javascript">https://eng.localytics.com/better-asynchronous-javascript</a></figcaption></figure><h3>#1 Callback (ES5)</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50dad6b23e523c9e7da5226b14710158/href">https://medium.com/media/50dad6b23e523c9e7da5226b14710158/href</a></iframe><p>The example is using ‘<em>https://jsonplaceholder.typicode.com</em>’ as a service provider to generate a legit JSON object for the demo. Suppose that we only want to return a list of ids, they are passed as an array object to the HTTP response. As you can see the ‘ids’ are in a completely new scope which makes whatever is defined in there less handy if the we would like to build on the ids later.</p><h3><strong>#2 Promise.all (ES6)</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3aecab1909b532a2b3c6c2a5543733/href">https://medium.com/media/6f3aecab1909b532a2b3c6c2a5543733/href</a></iframe><p>Promise.all uses the global promise object. ‘All’ methods accepts an array of promises, think of it as a group of (db create &amp; update) operations that run simultaneously but will resolve in different times. That method fires another promise object whenever all promises passed in the array are resolved/rejected. That’s definitely useful and better than the previous (callback) method, but is still creating new scope and isolating the results from the parental function. The next example will bring up a new resolution that maintains the running scope and shortens the written script for us.</p><h3><strong>#3 Async/Await (ES7)</strong></h3><p>This is part of the revolutionary newer Javascript specs. It uses promises to return the results and makes writing Javascript looks like synchronous scripting. Using this approach is a bit confusing for the ‘<em>Promises’</em> users as it consists of two steps. Step 1: calling a function that returns a ‘<em>promise</em>’ object. Step 2 wrapping the function calling the promise with a ‘async’ function, that returns ‘AsyncFunction’ object. This approach uses a couple of reserved words ‘<strong>async</strong>’ and ‘<strong>await</strong>’ as shown in the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d5a212add039f86f00c51020decd65/href">https://medium.com/media/a6d5a212add039f86f00c51020decd65/href</a></iframe><p>Wrapping the scope with a async function is a must, that was a missing and confusing part for me for a while when the ‘<em>async/await</em>’ was first introduced. Await is where the magic happens, we strip the entire crappy callback and assign the response, when resolved, to the defined ‘<em>const response = ..</em>’ Fetching the JSON ‘<em>users</em>’ object and extracting their ids in the example were all done in a single scope and made clean and easy compared to the previous messy examples. That’s what we were aiming for at the beginning but let us look at the next approach.</p><h3><strong>#4 Generator Functions (ES6)</strong></h3><p>Generators are functions that can execute part of a function, exited and then re-entered. When married with promises, generators can be a very powerful tool to rely on when working with promises.</p><p>There is an <a href="https://www.npmjs.com/package/co"><strong>npm module</strong></a> that simplifies working with generator functions named ‘<strong>co</strong>’. I personally think ‘co’ is a very powerful tool for a highly productive, efficient scripting and asynchronous interfaces. The following example gives a quick guide on how to use this module to extract the users JSON object again.</p><p>There are different ways in which generators can extract the response, but for brevity sake, we will only show a single way and will explore how that works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dff3f93bfca013f30cd0af4c112ad769/href">https://medium.com/media/dff3f93bfca013f30cd0af4c112ad769/href</a></iframe><p>The reserved word ‘<em>yield</em>’ is pretty much obvious, it is part of the generators implementation. Neat and clean? Yea. <strong><em>Why don’t we take a quick look on how that works by creating our version of ‘co’ and see how good is it?</em></strong></p><p><strong>Generators, Under the Hood<br></strong>Let’s create our own generator function* rather than relying on a module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8defe63530036d70e905957802cd39a1/href">https://medium.com/media/8defe63530036d70e905957802cd39a1/href</a></iframe><p>The passed generator function, as an argument, is stored as an ‘<em>IteratorFunction</em>’ instance to be called later. It will be the global iterator that pushes the results out from the generator function. Once iterator is set, we need to reach the part that stores the ‘<em>promise</em>’ from the ‘Iteration’ object, and then resolve it to iterate over the resolved promise content again to bring the final result.</p><p>If we clean up this mess and factor our function, it may look something like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f55145c4748fb37903c80e1670e1502/href">https://medium.com/media/7f55145c4748fb37903c80e1670e1502/href</a></iframe><p>Suppose that we’ve passed our lovely fetch as, a generator function, ‘(<em>function* () { fetch(‘…’) })</em>’, since that the argument is a function, executing it will not return the value immediately. Instead, it will return an iterator object that will be used to iterate over the values. Every time an iterator object is called, a promise is stored in the ‘value’ attribute. That promise will then need to be resolved to go to the next iteration. When the iterator function is finished, the flag ‘done’ is changed to ‘true’.</p><h3>Conclusion</h3><p>Eventually, it is the web developers call to stick with whatever he/she thinks is the most useful and beneficial for the written algorithm. I personally, think that generators are very powerful and the godfathers for the <em>async/await</em> implementation. Generators, when it was first released as a new es6 feature, it was like that person who packs his winter collection at the beginning of summer, ignored and thrown down the list for a greater focus on other useful specs.</p><p>I am sure there are many areas in which generator functions are of greatest benefits much like optimizing promises and callbacks. If you know any of these, you can list them in a comment and share the love.</p><p>Here is a list of good resources to get deep into the generators topic</p><ul><li><a href="http://2ality.com/2015/03/es6-generators.html">http://2ality.com/2015/03/es6-generators.html</a></li><li><a href="https://medium.com/dailyjs/a-simple-guide-to-understanding-javascript-es6-generators-d1c350551950">https://medium.com/dailyjs/a-simple-guide-to-understanding-javascript-es6-generators-d1c350551950</a> by <a href="https://medium.com/u/17f85189cad1">Rajesh Babu</a></li></ul><p>Special thanks to <a href="https://medium.com/@mpjme">Mattias Petter Johansson</a> for laying out a custom generator function, and also <strong>Typicode </strong>for their handy service.</p><p>All examples are available for public at <a href="https://github.com/khiami/fetch-examples.git">https://github.com/khiami/fetch-examples.git</a></p><p>Thanks for reading!</p><h4>References</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*</a></li><li><a href="https://kangax.github.io/compat-table">https://kangax.github.io/compat-table</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b6688cf7fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>