<?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 realdennis on Medium]]></title>
        <description><![CDATA[Stories by realdennis on Medium]]></description>
        <link>https://medium.com/@realdennis?source=rss-617335840e0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3alBHtQCdkLqFhqqKMh_6A.jpeg</url>
            <title>Stories by realdennis on Medium</title>
            <link>https://medium.com/@realdennis?source=rss-617335840e0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:32:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@realdennis/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[Stop Coding, Start Leading: How to Manage AI Agents Like Human Engineers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://realdennis.medium.com/stop-coding-start-leading-how-to-manage-ai-agents-like-human-engineers-fa020efec60c?source=rss-617335840e0c------2"><img src="https://cdn-images-1.medium.com/max/2600/0*WbdIk6ibeMsbVpL7" width="7680"></a></p><p class="medium-feed-link"><a href="https://realdennis.medium.com/stop-coding-start-leading-how-to-manage-ai-agents-like-human-engineers-fa020efec60c?source=rss-617335840e0c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://realdennis.medium.com/stop-coding-start-leading-how-to-manage-ai-agents-like-human-engineers-fa020efec60c?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa020efec60c</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 23:27:14 GMT</pubDate>
            <atom:updated>2026-08-25T23:30:01.973Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why Agentic Engineering is the New Frontend Blueprint]]></title>
            <link>https://realdennis.medium.com/why-agentic-engineering-is-the-new-frontend-blueprint-0a664912ab44?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a664912ab44</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Thu, 14 May 2026 12:57:53 GMT</pubDate>
            <atom:updated>2026-05-14T12:57:53.629Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last few months, a new term has infiltrated the developer lexicon: the <strong>“Vibe Coder.”</strong> It refers to a new breed of developer who doesn’t necessarily “write” code in the traditional sense, but rather “vibes” with an LLM until an application appears. To the “hardcore” computer science community, this looks like a joke. But to those who watched the evolution of the modern web, this looks like history repeating itself.</p><p>If you look closely, Agentic Engineering today is following the exact same lifecycle path that frontend development took over the last two decades. And if we want to understand where software engineering is going, we need to look at how we tamed the chaos of the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nC628YFJS8QCcG6v" /><figcaption>Photo by <a href="https://unsplash.com/@benkolde?utm_source=medium&amp;utm_medium=referral">Ben Kolde</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The “Index.html” Moment</h3><p>Everyone remembers the first time they saved a file as index.html, typed &lt;h1&gt;Hello World&lt;/h1&gt;, and saw it render. In that moment, the barrier to entry felt like zero. You weren’t just a hobbyist; you were a builder.</p><p>Agentic engineering is currently in its “Index.html” phase. Anyone can go to an LLM, say “Make me a budget tracker,” and — voilà — it exists. You have an app. You have “vibed” an agentic workflow into existence.</p><p>But there is a trap here. <strong>The prompt is cheap, and the generated code is cheap.</strong> The real value isn’t in the output itself, but in the <strong>engineering mindset</strong> required to make that output stable, repeatable, and scalable. A one-line prompt is a toy; a system of constraints is an engine.</p><h3>The Lifecycle of Complexity: Why Frameworks are Mandatory</h3><p>The comparison between frontend and agentic engineering works because they share a specific, painful lifecycle: <strong>The Simple Start vs. The Industrial Reality.</strong></p><ol><li><strong>The Toy Phase:</strong> You build a simple site with HTML/CSS. You build a simple agent with a single system prompt.</li><li><strong>The Business Requirement Phase:</strong> The client wants the sidebar to remember its state; they want the agent to check a database, call an API, and wait for human approval.</li><li><strong>The Industrialization Phase:</strong> Suddenly, “vibing” isn’t enough. You need <strong>determinism</strong>.</li></ol><p>Just as frontend developers realized that vanilla JS couldn’t handle complex state — leading to the rise of React and the “single source of truth” — agentic developers are realizing that “just prompting” can’t handle complex reasoning.</p><p>This is why we see the birth of frameworks or strictly and well tested skill sets. They are the Webpack and NPM of the agent world. They exist to provide the <strong>constraints</strong> that turn a non-deterministic LLM into a stable, predictable software system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xFlMrIHRPC8FvNAT" /><figcaption>Photo by <a href="https://unsplash.com/@arianismmm?utm_source=medium&amp;utm_medium=referral">Arian Darvishi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Cycle of Disdain: Why Purists are Wrong (Again)</h3><p>There is a long-standing tradition of backend and systems engineers, or even students looking down on frontend development. They viewed the churn of frameworks and the focus on “pixels” as inferior to “real” engineering.</p><p>Now, Agentic Engineering is encountering the exact same elitism. The purists argue:</p><ul><li>“It’s not real coding; it’s just talking to a box.”</li><li>“It’s non-deterministic and messy.”</li></ul><p>But history shows us a different truth: The frontend wasn’t hard because the language was bad; it was hard because <strong>the business requirements between humans and machines is inherently messy.</strong> Agentic engineering is the ultimate expression of that messiness. We are building systems that interpret vague human intent and turn it into strict machine execution. This isn’t “inferior” engineering — it is the hardest engineering problem we have.</p><h3>From Vibe Coding to Engineering Predictability</h3><p>When you move from being a “vibe coder” to an agentic engineer, you are defining <strong>Rules of Engagement</strong>.</p><p>In the React era, we learned that a stable UI is the result of State + Constraints. In the Agentic era, we are learning that a stable Agent is the result of Context + Rules.</p><ul><li><strong>Predictable Skills:</strong> Standardizing what an agent can do.</li><li><strong>Predictable Context:</strong> Ensuring the input-to-output loop is filtered through strict engineering logic.</li><li><strong>Predictable Quality:</strong> Moving away from “one-off” magic toward industrial-grade reliability.</li></ul><p>The frameworks that people complain about — the ones that make things “harder” — are the only thing making these systems viable for the real world. They provide the standardization that turns a creative toy into a reliable tool.</p><h3>Conclusion: The “Frontend-ification” of Software</h3><p>This isn’t just a lesson for frontend developers; it is a blueprint for the future of all software engineering.</p><p>We are entering an era where the primary challenge of coding is no longer syntax, but the <strong>management of uncertainty.</strong> The “CS Purists” may continue to dismiss agentic workflows as “just vibes,” but they said the same thing about high-level languages, about web frameworks, and about managed clouds.</p><p>History favors the builders who acknowledge the mess and build the constraints to tame it. Whether you come from a backend, systems, or frontend background, the shift is the same: We are moving away from writing instructions and toward <strong>engineering outcomes.</strong></p><p>The “vibe” era is over. The industrialization of the agent has begun — and it looks exactly like the revolution that built the modern web.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a664912ab44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[怎麼理解 microtask & macrotask]]></title>
            <link>https://realdennis.medium.com/%E6%80%8E%E9%BA%BC%E7%90%86%E8%A7%A3-microtask-macrotask-7754939b3c2c?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7754939b3c2c</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-api-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 22:39:10 GMT</pubDate>
            <atom:updated>2021-11-05T22:39:54.771Z</atom:updated>
            <content:encoded><![CDATA[<h4>雖然是面試常見題，但不要背誦答案，深入探索這個問題的本質，過程其實還蠻有趣的。</h4><h3>Definition</h3><h4>macrotask = task</h4><p>啊對，其實沒有所謂的 macrotask ，什麼<strong>宏</strong>任務、聽起來高大上的專有名詞，macrotask 這詞是為了對比 microtask 而誕生的，而它其實就是指向一般的 task ，什麼是 task 呢？ 啊就那些 <strong>event </strong>、 <strong>timer </strong>callback 等等的。</p><h4>那什麼是 microtask ？</h4><p>最常見的 microtask 就是 <strong>Promise </strong>， 當你的 task 裡頭出現了 Promise 的調用，這時 <strong>Promise 裡面的 callback 是不會被塞到我們熟知的 task queue</strong>，而是呀，其實內部還會有一個優先權更高的 micro task queue。</p><h3>Pseudo Code — event loop</h3><p>ref: <a href="https://github.com/atotic/event-loop#event-loop-description">https://github.com/atotic/event-loop#event-loop-description</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24ZxYuDXMqFnvP-Cbj_BBA.png" /></figure><p>我們把目光放在下面的 busy-waiting ，主要幹幾件事</p><ol><li>先 dequeue task</li><li>再 dequeue microtask</li><li>rendering</li></ol><p>那在 task 處理這些 callback 的時候，若裡面有夾帶 microtask 的 callback 就會被存放在 microtask queue，想當然它的優先權肯定是比一般 callback 高囉。</p><h4>Comparison case</h4><pre>setTimeout(()=&gt; console.log(&#39;timer&#39;),0) <br>// -&gt; enqueue in task queue</pre><pre>Promise.resolve().then(()=&gt;console.log(&#39;promise&#39;)) <br>// -&gt; enqueue in microtask queue</pre><pre>// output:<br>// promise (below the task queue done)<br>// timer (next while iteration)</pre><p>為什麼是這個順序呢？</p><pre>/** <br>our busy waiting logic...<br>while(true) {<br>    task = eventLoop.nextTask();<br>    if (task) {<br>        task.execute(); // now we execute above two line<br>    }<br>    eventLoop.executeMicrotasks(); <br>    // promise callback, print promise (1)<br>    if (eventLoop.needsRendering())<br>        eventLoop.render();<br>}<br><br>// timer (2) (next while iteration)</pre><pre>**/</pre><p>講破了好像就跟喝水一樣自然，畢竟常年使用 Promise 在處理非同步請求的 Engineer 可能下意識都有這種概念。</p><p>但其實沒有真正釐清兩者的話，總是會有奇妙的例子。</p><h4>Order inconsistent case</h4><p>wrap a cacheable fetch (inspired &amp; modified from <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#when_to_use_microtasks">MDN</a>)</p><pre>const cache = {};<br>const myFetch = url =&gt; {<br>  if (cache[url]) {<br>    console.log(cache[url])<br>  } else {<br>    fetch(url).then(result =&gt; result.arrayBuffer()).then(data =&gt; {<br>      cache[url] = data;<br>      console.log(data)<br>    });<br>  }<br>};</pre><pre>console.log(&#39;start&#39;);<br>myFetch(&#39;/test123&#39;)<br>console.log(&#39;done&#39;)</pre><p>這時一邊是 sync 一邊是 microtask：</p><p>cache hit</p><pre>start<br>cache result<br>done</pre><p>cache miss</p><pre>start<br>done<br>fetch result</pre><p>好像蠻合理的，但你不會想用到這種 order 異常的函式庫。</p><p>這時你可以選擇把上頭的同步工作非同步話，你有很多種選擇：0 ms timer / queueMicrotask / requestAnimationFrame blabla。</p><p>但你深知 fetch 後面就是 Promise chain ，這時有看文章的各位就知道可以用 microtask 來封裝一下</p><pre>const cache = {};<br>const myFetch = url =&gt; {<br>  if (cache[url]) {<br>    Promise.resolve().then(()=&gt;console.log(cache[url]))<br>  } else {<br>    fetch(url).then(result =&gt; result.arrayBuffer()).then(data =&gt; {<br>      cache[url] = data;<br>      console.log(data)<br>    });<br>  }<br>};</pre><p>這樣無論 cache hit or miss ， execution order 都會是</p><pre>start<br>done<br>result</pre><h4>還有哪些是 microtask ？</h4><p><strong>mutationObserver</strong> (see <a href="https://dom.spec.whatwg.org/#mutation-observers">WHATWG</a>) 、 <strong>queueMicroTask</strong> (See <a href="https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask">MDN</a>)</p><p>不過你去看 core-js 在完成 microtask 的時候，其實是彼此互相實作（有什麼用什麼） <a href="https://github.com/zloirock/core-js/blob/master/packages/core-js/internals/microtask.js#L41-L57">https://github.com/zloirock/core-js/blob/master/packages/core-js/internals/microtask.js#L41-L57</a>。</p><h4>RequestAnimationFrame 的 callback 跟這兩者的順序？</h4><pre>1. Do the oldest (macro) task<br>2. Do microtasks<br>3. If this is a good time to render:<br>   - Do some prep work<br>   - Run requestAnimationFrame callbacks<br>   - Render</pre><p>其實整篇文章可以參考這份 Spec<a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model"> https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model</a></p><p>不過我們可以看向 <strong>8.1.6.3–11.13</strong> 在 render 階段他會去把 <strong>animationFrames </strong>的 callback 抓出來開始 dequeue，並且把 timestamp 傳進去。</p><p>其實這部分跟最上頭貼的 pseudocode 是一致的，可以看一下 render 的 method 。</p><p>我覺得整段虛擬碼概括了整個 Event loop 到底發生了什麼。</p><h3>尾聲</h3><p>想粗淺的了解 event loop 在瀏覽器的模型是什麼，我推薦看這部影片：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8aGhZQkoFbQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8aGhZQkoFbQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8aGhZQkoFbQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a661a28c8cc4ab11cdfc9f9487ebd139/href">https://medium.com/media/a661a28c8cc4ab11cdfc9f9487ebd139/href</a></iframe><p>我覺得講的很詳細也很好懂。他的 DEMO 真的生動，你大概就能了解 call stack ， 還有 event / timer 到底發生什麼事了。</p><h4>補充</h4><p>因為在討論串瞄到，似乎有些誤用文章將 stack and queue 與 call stack / task queue 誤用。</p><p>我建議可以回頭學習的基本學科：</p><ul><li>資料結構（Chapter: stack &amp; queue / Heap, priority queue）</li><li>作業系統（Chapter: Scheduling / Synchronization）</li></ul><p>尤其是 OS 的 Scheduling ，或許會對 event loop 感覺豁然開朗。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7754939b3c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 3 useful methods in JavaScript function prototype— call, apply, bind]]></title>
            <link>https://realdennis.medium.com/top-3-practical-methods-in-javascript-function-prototype-call-apply-bind-33e03a46101?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/33e03a46101</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[this]]></category>
            <category><![CDATA[javascript-arrow-function]]></category>
            <category><![CDATA[ecmascript-6]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Sun, 23 May 2021 00:04:08 GMT</pubDate>
            <atom:updated>2021-05-23T05:22:09.627Z</atom:updated>
            <content:encoded><![CDATA[<h4>There’re three similar methods in Function.prototype, call, apply and bind, these three methods could change the dynamical `this` in function, I’ll not talk too much about `this`, but more about these methods’ ins and outs.</h4><p>Chinese: <a href="https://realdennis.medium.com/javascript-%E8%81%8A%E8%81%8Acall-apply-bind%E7%9A%84%E5%B7%AE%E7%95%B0%E8%88%87%E7%9B%B8%E4%BC%BC%E4%B9%8B%E8%99%95-2f82a4b4dd66">[JavaScript] 函數原型最實用的 3 個方法 — call、apply、bind</a></p><p>So, in this article, I’ll do compare with a(apply) / b(bind) / c(call), and little bit concept of function `this`, in last, will take a practical use case about self, bind, arrow function.</p><p>Let’s start our trip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WYa5eVZxAJ7eXxXH" /></figure><h4>Why we need apply / bind / call ?</h4><p>JavaScript (so called ECMAScript) is a dynamic programming language, the “dynamic” sounds abstract, you might think “yeah … but I also learned other dynamic programming languages”, but the point is, the function `this` is dynamic.</p><p>Let’s see the common use case of apply / bind / call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76ff71d26ad7e6770f5d9f4b15aa78df/href">https://medium.com/media/76ff71d26ad7e6770f5d9f4b15aa78df/href</a></iframe><p>You’ll get the same output, these three can do the same thing as L8–9.</p><h4>Please tell me what’s the magic behind these three methods!</h4><p>Let’s classify to call, apply vs bind :</p><ul><li>call, apply return function result</li><li>bind method return the function with binding `this`</li></ul><p>We can figure out that bind method doesn’t wanna call the function.</p><h4>The usage of Function.prototype.call()</h4><blockquote>The <strong>call()</strong> method calls a function with a given this value and arguments provided individually. （src. MDN）</blockquote><p>Honestly, I do not really understand it when I first saw this…</p><p>As my words, we can just shift the `arguments` to right, and tell the function `this` what we wanna use in the first parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*2sqeMLm9iUr-ildj" /><figcaption>Translated: The word B what u want (sometimes B point out the something you show off in Chinese)</figcaption></figure><p>Except the first parameter, it’s 87% similar as original function call:</p><blockquote>func(1, 2, 3) vs func.call(null, 1, 2, 3)</blockquote><h4>So, Function.prototype.apply() is just a shortcut</h4><pre>func.apply(thisArg, [argsArray])</pre><p>The interface of apply() only receive two parameters, you know the first one (yup, `this` again), and the second one is the arguments but it’s array.</p><blockquote>func( 1 , 2 , 3 ) vs func( null , [ 1 , 2 , 3 ] )</blockquote><p>A special point, there’s a preserve variable `arguments`, it’s array, so if you use `apply` method, you don’t need to do destructuring assign :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa8d0ce72d2644b3c8e8d32746df960/href">https://medium.com/media/2fa8d0ce72d2644b3c8e8d32746df960/href</a></iframe><p>Just said, in the upper use case, we can easily solve that using `bind`.</p><h4>How’s Function.prototype.bind()?</h4><p>When you search on web, you’ll find out there’re thousands article wanna tell you how awesome you can do `currying` with `bind` method, why it’s a good practice, bla bla…</p><p>Let’s deep dive in bind, what bind want to do.</p><p>bind — different from the upper two, we don’t need pass the function’s parameter, and it’ll not return the result either, it’ll return “A function with the fixed this what you pass”, yes fixed, when you do, you cannot change the function `this` anymore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23e2c45a5e8bb238cc22d3a33e17d274/href">https://medium.com/media/23e2c45a5e8bb238cc22d3a33e17d274/href</a></iframe><p>In L6, we bind the function wtf_bind_window first, so this function use the fixed this — window, you cannot change anymore even call, apply, or do bind again.</p><h4>Do you really need bind()?</h4><p>This is a classic case, you might have seen that when you make a callback function in class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d72a4207cac7e453f6411f5c8d765381/href">https://medium.com/media/d72a4207cac7e453f6411f5c8d765381/href</a></iframe><p>When you running the `laterHello`, the timer callback cannot get the correct this (which should point out to class instance), you can see it’s a very common case in Node’s class and React / Vue ’s class component.</p><p>There’re 3 ideas to solve this, `bind` is the one, but not the best one:</p><p><strong>1 Self </strong>— something the JS developer love to use in class…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28ba214b532a4be284f5b113659c5bb/href">https://medium.com/media/f28ba214b532a4be284f5b113659c5bb/href</a></iframe><p>When you maintain the legacy project, you’ll see this most time.</p><p>Why I put it in the first one? Since it’s the low thinking cost solution, just use self, just follow the original pattern, no magic, no error, and easily review.</p><p><strong>2 Binding</strong> — yup, so after reading this article, you have another choice</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/490b75292a729d404888844eaf4ea9c3/href">https://medium.com/media/490b75292a729d404888844eaf4ea9c3/href</a></iframe><p>In this solution, there’s a big advantage of it, you don’t need to do any change in the inner callback function, but just tell what’s the correct `this` you want to apply.</p><p>In real world you don’t want to do much change but just reuse the function in callback, it might has much `this` you need to update to `self`.</p><p>But there’s another solution after ES6.</p><p><strong>3 Arrow function </strong>— ikr, you don’t want self, but bind is hard to learn.</p><blockquote>There’s a best thing in JavaScript that if you don’t want to learn a feature, you can just drop it out, there’s another different pattern to solve the same scenario. LMAO.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf6a000409707c7555c40a7001c48353/href">https://medium.com/media/bf6a000409707c7555c40a7001c48353/href</a></iframe><p>In most cases, arrow function has no difference from normal function, the only special is, the function `this` of arrow function always point out the context scope, and it’s fixed, even you do apply, bind and call, arrow function always got the this from context scope.</p><h4>Conclusion</h4><p>I finally finish this article, the best profit of writing articles is that I could understand more clear when introducing to others, hope you guys love it!</p><p>And next time you learn something like currying or function this, you can just refer from this article, hope it helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33e03a46101" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design responsive layout system using only 40 lines —Know how to implement col-sm-12 and col-md-6]]></title>
            <link>https://realdennis.medium.com/design-responsive-layout-system-using-only-40-lines-know-how-to-implement-col-sm-12-and-col-md-6-4da955b61387?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da955b61387</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[flex]]></category>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[flexbox]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Fri, 21 May 2021 22:03:28 GMT</pubDate>
            <atom:updated>2021-05-21T22:52:41.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you’ve used Bootstrap, you’ve must applied some class name like these for responsive web design(RWD), would you want to know how it works? Let’s step by step to find the magic behind this!</h4><p>Chinese version: <a href="https://realdennis.medium.com/40%E8%A1%8C%E5%AF%A6%E4%BD%9C%E9%9F%BF%E6%87%89%E5%BC%8F%E7%9A%84%E4%BD%88%E5%B1%80%E7%B3%BB%E7%B5%B1-%E5%91%8A%E8%A8%B4%E4%BD%A0col-sm-12-col-md-6-%E6%98%AF%E5%A6%82%E4%BD%95%E5%AF%A6%E7%8F%BE-4490a65b1a0">40行實作響應式的佈局系統 — 告訴你col-sm-12、col-md-6 是如何實現</a></p><h3>realdennis on Twitter: &quot;Last night I Implemented a simple grid system, that wasn&#39;t difficult, if you familiar with flex! But, I thought I&#39;ll choose display:grid next time... 🤯https://t.co/qheyKti08L#css #flex #grid #responsive #rwd pic.twitter.com/4vhadSxuXh / Twitter&quot;</h3><p>Last night I Implemented a simple grid system, that wasn&#39;t difficult, if you familiar with flex! But, I thought I&#39;ll choose display:grid next time... 🤯https://t.co/qheyKti08L#css #flex #grid #responsive #rwd pic.twitter.com/4vhadSxuXh</p><p>To read this article, <strong>you don’t need:</strong></p><ul><li>Solid coding skill or JavaScript ability</li></ul><p>But<strong> you need:</strong></p><ul><li>Understanding for-loop, I’ll use SCSS to do the duplicated operations</li><li>Known SCSS &amp; is point to the nested element</li><li>Known about CSS Flex</li><li>Known media query</li></ul><blockquote>This article is for someone like me, who wanna find out the responsive implementation in book shop, but most books only teach “how to use Bootstrap“, lol.</blockquote><h4>About Bootstrap Grid system</h4><p>For the user who are not familiar with front-end, the bootstrap is really helpful to do the layout, by adding class name like .row / .col / .col-sm-3, we can easily put the container/element to the corresponding size and ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tFEUgAsN3TVXoQPt.png" /><figcaption>src. Bootstrap Document</figcaption></figure><p>You can see the usage in official documents, you don’t even have to write a line of CSS:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      1 of 2<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      2 of 2<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      1 of 3<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      2 of 3<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col&quot;&gt;<br>      3 of 3<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Except helping to do layout, Bootstrap provide the <strong>breakpoint</strong>, we can make the element be responsive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8wr2Xy_kUENxpEl9.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bFTnfq5edUAtuoU7.png" /><figcaption>wide screen vs narrow screen</figcaption></figure><p>We notice that:</p><ul><li>There’s multiple rows in narrow screen</li><li>In corresponding place by ratio</li></ul><p><strong>And you can using the same one HTML to fulfill different device, it’s so called RWD.</strong></p><p>By the increasing rate of mobile user, website developer start to focus on better experience for small device (compare to desktop), I thought no one want to keep resizing when browsing the site.</p><h4>Implementation</h4><p>The following two items we want to implement are:</p><ol><li>Layout, multiple columns in row, automated grow width (1:1:1)</li><li>Responsive, using different ratio by breakpoint</li></ol><h4><strong>Layout — row and column</strong></h4><p>Let’s back to check the simple example, it should be like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*T3qU-YTZsAq-gu1N.png" /></figure><pre>.row{<br> /**<br> * Do what?<br> * display : ??;<br> *<br> * wrap to next line?<br> * ??????? : wrap;<br> **/<br>}</pre><p>Okay, it’s actually trivial … I just wanna align the left image haha, basically you know the answer if you know the CSS flex.</p><pre>.row {<br> display: flex;<br> flex-wrap: wrap;<br>}<br>.col{<br> flex-grow: 1;<br> margin: 15px;<br>}</pre><p>Just mentioned, when we don’t have breakpoint, we hope the column could <strong>grow up</strong>, in another word, we want fill out the whole row, so we define flex-grow: 1;.</p><p>Since each column’s flex-grow is 1, so the rest space would be filled by 1:1:…:1.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Frealdennis%2Fembed%2Fpreview%2FzXZOqm%3Fheight%3D600%26slug-hash%3DzXZOqm%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Frealdennis%2Fpen%2FzXZOqm%3Feditors%3D1100&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e65950e4f8fa51f5816c1a7c5f203a64/href">https://medium.com/media/e65950e4f8fa51f5816c1a7c5f203a64/href</a></iframe><p>To show the flex-wrap, I set a min-width to 200px, so you can try to set your width smaller than 600px, the exceed column item would be wrap to next line.</p><p>A good beginning is half the battle.</p><h4>Responsive (1. ratio) — col-1~col-2</h4><p>We have all 12 grids at all, let’s calculate in each case.</p><p>There’s a convenience stuff — for loop, <strong>not gonna lie, I basically search for-loop usage in SCSS for implement this…</strong></p><p>By the way, there’re some preprocessor for making stylesheet, you might think it’s not really helpful or only using nested, variables, but in developing framework-like system, it plays a good role.</p><p>Let’s make different width value by ratio:</p><pre>@for $i from 1 through 12 {<br> .col-#{$i} {<br>  flex-grow:0;<br>  flex-basis: calc(-30px + 100% *#{$i}* 1/12);<br> }<br>}</pre><p>So now, we canceled the flex-grow, since we want it keep the ratio.</p><p>Others, we set the columns width in ratio by flex-basis and CSS3 calc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cBnicwJL_op20Eek.png" /><figcaption>3 : 2 : 5 : 2</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Frealdennis%2Fembed%2Fpreview%2FXQMrow%3Fheight%3D600%26slug-hash%3DXQMrow%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Frealdennis%2Fpen%2FXQMrow%3Feditors%3D1100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F2572318.XQMrow.small.fcc94b0a-2663-4d54-9273-608b37a6ed35.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f29640d3bb0b47a2354798a2e17a91/href">https://medium.com/media/31f29640d3bb0b47a2354798a2e17a91/href</a></iframe><p>Just change the number after col-, and see the result! If there’s a col exceed to 12, it’ll be wrap in next line.</p><h4>Responsive (2. breakpoint) — what’s the sm, md, lg?</h4><p>We don’t need to find the answer in urgent, let’s think in same figure as above, think what it represent for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3eewQ_EhhzkDMTZ2.png" /></figure><p>Use a simple logic to think, we always want we have the more columns in large width, and only one column in smaller width (like smartphone), the reason is — we don’t want content small.</p><p>If you’re an engineer use bootstrap in usual, you can know this at first sight, by see the other developer do in RWD site, will always see:</p><pre>&lt;div class=&quot;col col-12 col-sm-6 col-md-4 col-lg-2&quot; /&gt;</pre><p>In non-nerd words:</p><p>— Very narrow width device? One column fills the whole 12 grids!</p><p>— Not narrow? but also not wide? One column fills 6 grids!</p><p>— Wide and large device? One columns fills 2 grids!</p><p>If we have 6 columns, it would be like:</p><pre>// &lt;sm<br>12<br>12<br>12<br>12<br>12<br>12</pre><pre>// sm<br>6 6<br>6 6<br>6 6</pre><pre>// md<br>4 4 4<br>4 4 4</pre><pre>// lg<br>2 2 2 2 2 2</pre><p>So … What’s the very small? What’s the very large? Actually it’s defined in document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rpNFatZEYjxYZKiU.png" /></figure><h4>Let’s add these conditions</h4><p>We all know about there’s a thing’s named media query could help us define style rule in different device width, but what’s the rule we need?</p><p>Actually it has the same behavior in each media query, as <strong>Responsive(1. ratio) does</strong>, we just give the width by the ratio number.</p><p><strong>Think you think… by the same figure.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LATOz_XUmdwhrOR4.png" /></figure><p>Even we have multiple class name, we only care about that’s width in corresponding size!</p><p>Let’s just jog down in different breakpoint:</p><pre><a href="http://twitter.com/media">@media</a> (min-width: 576px) {<br>    <a href="http://twitter.com/for">@for</a> $i from 1 through 12 {<br>      &amp;.col-sm-#{$i} {<br>        //grow、basis...blabla<br>      }<br>    }<br>}<a href="http://twitter.com/media">@media</a> (min-width: 768) {<br>    <a href="http://twitter.com/for">@for</a> $i from 1 through 12 {<br>      &amp;.col-md-#{$i} {<br>        //grow、basis...blabla<br>      }<br>    }<br>}.<br>.<br>.</pre><p>That’s so called responsive breakpoint, let’s see the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Frealdennis%2Fembed%2Fpreview%2FqwRLRY%3Fheight%3D600%26slug-hash%3DqwRLRY%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Frealdennis%2Fpen%2FqwRLRY%3Feditors%3D0100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F2572318.qwRLRY.small.1714a9bc-6d71-4ce9-97bf-695bf6ed86e9.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e560836bea03f02e7be1522d12248a8/href">https://medium.com/media/7e560836bea03f02e7be1522d12248a8/href</a></iframe><h4>Conclusion</h4><p>I could tell you this grid system I design would be the ugliest code, since it’s for tutorial purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t2zpiq6qmFqZLKmX.png" /><figcaption>Yup, we step by step to finish the general responsive design system!</figcaption></figure><p>In this implementation, I learn some lessons, making a RWD system is not hard as I image at first, jut hold the basic CSS property, flex.</p><p>And the core code only in L38–87, plus all the behaviors are the same in different breakpoint, I try not to use too much SCSS syntax, so it’s hardcore RWD system in the world I think…</p><p>Maybe next time, you want make RWD, you don’t really need Bootstrap!</p><h4>Let’s check the answer with Bootstrap <a href="https://github.com/twbs/bootstrap/blob/19aee321a027edaa60c3087bfcf6c9f1517c9b98/dist/css/bootstrap-grid.css#L279-L282">source code</a></h4><pre>.col-sm-2 {<br>    flex: 0 0 16.666667%;<br>    max-width: 16.666667%;<br>}</pre><p>So the behavior is the same as what we do calc!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da955b61387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand var and let in JavaScript in 2 minutes]]></title>
            <link>https://realdennis.medium.com/understand-var-and-let-in-javascript-in-2-minutes-3fe493cf7c9f?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fe493cf7c9f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Thu, 20 May 2021 22:32:21 GMT</pubDate>
            <atom:updated>2021-05-20T22:32:21.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you’re a JavaScript beginner, you might have a question: why there’re too much way to declare the variable: “var” declaration from ES5, “let” and “const” from ES6, we can easily know “const” is for constant value, but what’s the difference between “var” and “let”?</h4><p>Chinese: <a href="https://realdennis.medium.com/%E9%96%92%E8%81%8A-var%E8%88%87let%E7%9A%84%E6%87%B6%E4%BA%BA%E5%8C%85-javascript-b5a3f40ee28d">用 1 分鐘簡單地了解 — JavaScript中 var 與 let 的主要差別</a> &amp; <a href="https://realdennis.medium.com/%E4%B8%80%E6%AC%A1%E8%AA%AA%E6%B8%85%E6%A5%9A-javascript-%E4%B8%AD%E5%AE%A3%E5%91%8A%E7%9A%84%E5%90%84%E7%A8%AE%E6%8F%90%E5%8D%87%E8%A1%8C%E7%82%BA-var-function-let-const-dd9175d063f0">一次說清楚 JavaScript 中宣告的各種提升行為</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZSGhyJRPdrHB32jy" /></figure><blockquote>let/const: { block scope }<br>var: function(){</blockquote><blockquote>function scope</blockquote><blockquote>}</blockquote><blockquote>Global →Function → Block</blockquote><h4>Summary</h4><ul><li>They have different scope “<strong>var” is scoped in function, “let” is scoped in block.</strong></li><li><strong>Hoisting</strong> in “var”</li><li><strong>Temporal Dead Zone</strong> in “let”</li></ul><h4>Scope</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fe64f5f4f7d621c1864f43feb6898f2/href">https://medium.com/media/9fe64f5f4f7d621c1864f43feb6898f2/href</a></iframe><p>What interesting is, L12 also get the ReferenceError , it’s similar as L6, we cannot access the variable out of scope.</p><h4>Hoisting</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0966e61e96919513a38ceb813855283/href">https://medium.com/media/c0966e61e96919513a38ceb813855283/href</a></iframe><p>In the L2–5, we can found that variable1 has been hoisted, so there’s no reference error be thrown out.</p><p>What the actual for L2–5:</p><pre>(function(){<br>  var variable1;<br>  console.log(variable1); // undefined<br>  variable1 = 20;<br>}())</pre><h4>Temporal Dead Zone</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df43d19c46c92596c1d2b00cab3ad0b6/href">https://medium.com/media/df43d19c46c92596c1d2b00cab3ad0b6/href</a></iframe><p>L1–6, we cannot repetitive declare the same variable in same scope, that’s the <strong>TDZ</strong> for let.</p><p>But we can do that using var.</p><h4>Conclusion</h4><p>Just image that when you’re in elementary school, the classmate sit close to you always did that: “Hey, I mark a line between us, just don’t across that!”</p><p>Right, that’s the concept of <strong>scope</strong>, in your own place, even you two put the same math book, but you’ll not take the wrong one.</p><p>How the mess if scope is bigger?</p><p>You can ask your big brother/sister, how they allocate the properties like house, cars, etc. after getting married, lol.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fe493cf7c9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用八二法則寫 custom react-hooks]]></title>
            <link>https://realdennis.medium.com/%E7%94%A8%E5%85%AB%E4%BA%8C%E6%B3%95%E5%89%87%E5%AF%AB-custom-react-hooks-d61495629365?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61495629365</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Thu, 20 May 2021 12:02:26 GMT</pubDate>
            <atom:updated>2021-05-20T12:02:26.290Z</atom:updated>
            <content:encoded><![CDATA[<h4>根據八二法則，只需要兩成的功就能滿足八成的事，那我們來用兩成的 built-in hooks 來封裝八成我們會用到的 custom hooks 吧！</h4><h4>寫在文前</h4><p>這不是一篇正經的 react-hooks 知識點文章，更多的反而是我的 murmur 跟一些對於 hooks 怎麼從無到有的一點思考路線。而下半段會做 code-reviewing。</p><h4>內建的 hooks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*GZM1I8JMixvhdGWAH-Lbpw.png" /><figcaption><a href="https://zh-hant.reactjs.org/docs/hooks-reference.html">https://zh-hant.reactjs.org/docs/hooks-reference.html</a></figcaption></figure><p>這麼多 hooks ，分別：</p><ul><li><strong>控 state 的</strong> （useState 、 useReducer 、 useContext）</li><li><strong>控 Effect 的</strong>（useEffect 、 useLayoutEffect）</li><li><strong>控 ref 的</strong>（useRef 、 useImperativeHandle）</li><li><strong>優化</strong>用的（useMemo 、 useCallback）</li><li><strong>Debug</strong> 用（ useDebugValue， 我沒用過）</li></ul><p>由於八二法則的原因，所以我們就從十個 hooks 挑兩個來用吧！</p><p>useState &amp; useEffect，必要時我們再挑其他的進來打組合拳。</p><h4>useState &amp; useEffect 在幹嘛？</h4><p><strong>一個控 state ，state 變了組件就會更新，更新就會有 effect 觸發，最後組件 unmount 再把 effect 全部清掉。</strong>這就是一個簡單的函數組件會發生的小事。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTOXkEla_wqH0y1GSDaywQ.png" /><figcaption>A trivial component use hook</figcaption></figure><p><strong>L4</strong>: 設定初值並回傳 state 的 getter setter</p><p><strong>L6-L7</strong>: 在這邊寫下狀態 update 之後可能會造成環境髒亂的 Effect code。（如attach event、修改樣式）</p><p><strong>L8-L12</strong>: 組件unmount 幫 L6-L7 造成的 Effect 擦屁股。（如detach event）</p><h4>會這兩個 hook 還能幹嘛？</h4><p>好，看完以上文檔 -like 的廢話，我們開始切入正題，到底如何八二法則的寫一個自己的 custom hook。</p><p>讓我們用 <a href="https://github.com/streamich/react-use/tree/90e72a5">react-use</a> 這個 react hooks opensource 專案來舉例子吧！</p><ol><li>優雅地拿外部（window）滾動狀態——<a href="https://github.com/streamich/react-use/blob/90e72a5/src/useWindowScroll.ts">useWindowScroll</a></li><li>優雅地拿外部（window）的 size ——<a href="https://github.com/streamich/react-use/blob/90e72a5340460816e2159b2c461254661b00e1d3/src/useWindowSize.ts">useWindowSize</a></li><li>優雅地拿外部（裝置）電量狀態——<a href="https://github.com/streamich/react-use/blob/90e72a5/src/useBattery.ts">useBattery</a></li></ol><p>那我們開始前，由於你知我知獨眼龍也知， code 總是會有更動，加上這篇文章主要是 reviewing 性質，我們依照發文當下的 HEAD 90e72a5 ，而你們點進去的連結會直接切近這個 commit hash 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtCXgRorz7LwbQdwVmpJFQ.png" /></figure><p><strong>useWindowSroll</strong></p><p><a href="https://github.com/streamich/react-use/blob/90e72a5/src/useWindowScroll.ts">streamich/react-use</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*W5ILnzqW3jhEPOQXDtBQuw.png" /></figure><p>L11-L15 (useState)： 設定 state</p><p>L17-L46 (useEffect)：實際上在做的只要兩件事</p><ol><li>(effect) attach event</li><li>(cleanup) detach event</li></ol><p>這是一個 event relative 的 custom hook 的一個常見 Flow。</p><p>注意，他們的 comparedArray 是[]，意味著只有一開始跟最後會觸發 useEffect，也就是說<strong> mounted-&gt;attach</strong> v.s<strong> unmounted-&gt;detach。</strong></p><p>最後 event callback 做了什麼呢？就是在 scroll event trigger 的時候把新的 pageXOffset / pageYOffset寫進 state。</p><p>就是這麼簡單</p><p><strong>useWindowSize</strong></p><p><a href="https://github.com/streamich/react-use/blob/90e72a5340460816e2159b2c461254661b00e1d3/src/useWindowSize.ts">streamich/react-use</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*_40A_uK7Dzh27hIExI32cw.png" /><figcaption>注意 L27，comparedArray 依然是 [] ，所以只會在 mounted 時 attach ， unmounted detach event。</figcaption></figure><p>L7–10(useState)：我們會用到寬高</p><p>L12–30(useEffect)：其實跟偵測 scroll 狀況大同小異</p><ol><li>(effect) attach window event, resize 。</li><li>(cleanup) 把上述 event detach 掉。</li></ol><p><strong>useBattery</strong></p><p><a href="https://github.com/streamich/react-use/blob/90e72a5/src/useBattery.ts">streamich/react-use</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*6JFw-83pn4MQ1BzDeGDeKg.png" /><figcaption>注意 L78 ，comparedArray 依然是 [] ，所以只會在 mounted 時 attach ， unmounted detach event。</figcaption></figure><p>L36 (useState)：isSupported &amp; fetched</p><p>L38-L76 (useEffect)：雖說是 device info ，但實際上也是透過 browser 提供的 event 去偵測電量變化。</p><ol><li>(effect) attach events，包括 chargingchange, chargintimechange, dischargingtimechange, levelchange</li><li>(cleanup) 把上述四個 event detach 掉。</li></ol><p>至於這四個 event 究竟做了什麼，可以參考這頁 MDN 的<a href="https://developer.mozilla.org/en-US/docs/Web/API/BatteryManager">文檔</a>。</p><p>（不過你可以看到 MDN 不太推薦你使用就是了。）</p><p>你會發現，<strong>啊乾，怎麼三個長的差不多？</strong> （不然我怎麼會說八二法則）</p><p>他們都是在藉由各物件（像 window 、 document 、 batteryManager）的 event 來實時地 monitor 外部的 value 。</p><ul><li>註冊 event 到 react element （onClick），react 在 lifecycle 結束後會幫你清除掉。</li><li>註冊在外部的（addEventListener），如果你沒有手動清除，它就會一直掛在那，這種就是 side-effect 。</li></ul><p>所以 cleanup function 就是個擦屁股的角色 lol。</p><h4>useRef</h4><p><strong>如果你會寫 class component</strong>，你一定曾經幹這種事 this.count = 20 ，整個class component 因為 share 這個 this， 所以都可以 access 到，<strong>且不會驚動到 re-render</strong>。</p><p><strong>如果你不常寫 class component</strong>，那麼很多時候 temp value 是不需要觸發組件更新的，比如跟組件更新無關的變數 、 element ，這些跟組件更新沒啥關係的東西。</p><p>是的，useRef 就是幫你完成這件事情的，<strong>雖然函數組件可以直接宣告變數，但每次 render 又會再重新 declare 一次</strong>，<a href="https://stackoverflow.com/questions/56553236/differences-between-useref-and-ref-variable-in-reactjs">see this</a>。</p><p><a href="https://zh-hant.reactjs.org/docs/hooks-reference.html#useref">React 文檔的例子</a>：</p><pre>function TextInputWithFocusButton() {<br>  const inputEl = useRef(null);<br>  const onButtonClick = () =&gt; {<br>    // `current` points to the mounted text input element<br>    inputEl.current.focus();<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;input ref={inputEl} type=&quot;text&quot; /&gt;<br>      &lt;button onClick={onButtonClick}&gt;Focus the input&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>第一次走完之後 inputEl.current 就會指向這個 input element。</p><h4>繼續我們的 code reviewing 之旅吧</h4><ol><li>優雅地改 document title —— <a href="https://github.com/streamich/react-use/blob/90e72a5340460816e2159b2c461254661b00e1d3/src/useTitle.ts">useTitle</a></li><li>優雅地將 throttle 密集變動的 props ——<a href="https://github.com/streamich/react-use/blob/90e72a5340460816e2159b2c461254661b00e1d3/src/useThrottle.ts">useThrottle</a></li></ol><p><strong>useTitle</strong></p><p><a href="https://github.com/streamich/react-use/blob/90e72a5340460816e2159b2c461254661b00e1d3/src/useTitle.ts">streamich/react-use</a></p><p>我寫到這，發現現在的版本有 bug （commit hash 90e72a5） ，我發 <a href="https://github.com/streamich/react-use/pull/2010">PR</a> 過去修了，先 skip。</p><p><strong>useThrottle</strong></p><p><a href="https://github.com/streamich/react-use/blob/90e72a5340460816e2159b2c461254661b00e1d3/src/useThrottle.ts">streamich/react-use</a></p><p>useThrottle 要 review 之前，要先來理解一下 document：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*zqQKVVfazC6LYurTgEEdeA.png" /><figcaption>ref: <a href="https://github.com/streamich/react-use/blob/8ceb4c0f0c5625124f487b435a2fd0d3b3bc2a4f/docs/useThrottle.md">useThrottle docs</a></figcaption></figure><p>簡單來說，useThrottle 的目的在於將密集變動的 props throttle 的方式變成 state 。</p><p>我們先不考量這樣的利弊去做 Review（我個人會傾向在第一個產生 props.value 那層，就先 throttle &lt;Demo value={throttleValue}/&gt; ，而非 throttle props）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*WcwtCagp_uw0OInPcamE3Q.png" /></figure><p>L6–8 我們把 timer id 、 nextValue 、 hasNextValue 存在 useRef 裡面，他們跟 timer 是否重新設定、在裡頭的值有關，但這些跟組件的 state / rendering 無關。</p><p>整個 custom hook 的 flow 是這樣：</p><ol><li>value change，設定一個計時器幫我更新（也許200ms）</li><li>若 1. 還沒執行 timer callback，有 value 的 update ，則進入 L23-25，將其設為下一個被設定的 nextValue</li><li>若 1. 2. 還沒執行，有新 value update，則進入 L23–25 ，nextValue 被 override 為最新值（意味著 2. 被 throttle 掉囉）</li></ol><p>在這個例子中，以 nextValue 、 hasNextValue 這些變數而言，沒有排到隊根本就沒有進到 state 造成額外 re-render 成本上升的必要。</p><h4>尾聲</h4><p>如何？在這樣的旅程裡，你透過兩成的 hooks 就能做簡單的 code reviewing，挺有成就感的吧！</p><p>我記得 hooks 剛出來的時候，有一些人覺得 hook 可以讓 react 做很多事，但其實沒有哇，你可以看到那些很特別的功能（比如 battery），跟 hook 本身沒有關係。</p><p>封裝 Hook 的代碼行數比起 class component 特別拆週期去實作較短、明確，但其實常常會犯錯，官方的 <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">lint rule</a> 是一個很好的輔助工具。也可以透過 <a href="https://zh-hant.reactjs.org/docs/strict-mode.html">React 嚴格模式</a>，來測試其可用性與穩定性。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61495629365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React SSR: initial data fetching & hydrate]]></title>
            <link>https://realdennis.medium.com/react-ssr-initial-data-fetching-hydrate-2e2063c51663?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e2063c51663</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Sat, 08 May 2021 21:44:16 GMT</pubDate>
            <atom:updated>2021-05-08T22:06:09.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>試想你用 React 刻了一個論壇的 Single Page App，但是為了 SEO / Performance 考量，你決定第一畫面的文章列表在 server side 先 render 出來，這時該怎麼做？</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95lspV917PYehJ9g2C8UHg.png" /><figcaption>server-side fetching data from reddit endpoint</figcaption></figure><h4>寫在文前</h4><p>自己組一套 React server side rendering 其實蠻多文章的，也有翻到不錯的手把手教學文（真的很讚），但多數好像都只有教你弄出畫面，然後畫面上有 React 的功能，卻沒有做到封裝、傳入 data fetching / getInitialProps 這段。</p><p>這篇不是手把手的教學文，而是以<strong>最暴力</strong>的方式告訴你現有工具如何去<strong>拉+打解決 SSR data fetching / initial props </strong>。</p><p>閱讀之前我們要有個共識：</p><ul><li>你碰過、寫過、蹂躪過 SSR 的 framework ，想知道如果自幹的話 markup 與 state/props 怎麼丟給 User client side</li><li>你知道 hydrate 是在幹嘛，它長的跟 <strong>ReactDOM.render</strong> 87% 像，但他負責跟 renderToString打組合拳</li></ul><p>以下全部都是虛擬碼，請斟酌閱讀。</p><blockquote>更新：我照著自己的脈絡刻出來的專案 <a href="https://github.com/realdennis/react-ssr-reddit-meme">https://github.com/realdennis/react-ssr-reddit-meme</a> 可以參考一下。</blockquote><h4>Step 0— File structure</h4><pre>├── client.js #主要是 hydrate logic<br>├── package.json <br>├── server.js <br>└── src <br>    └── index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LIXPUz51Z8qbjdWS" /></figure><h4>Step 1—Server-side fetch data</h4><p>原本我們在 CRA 設計出來的論壇 App 會在 client-side 去 call endpoint 。</p><p>大概原本是長這樣：</p><p><strong><em>client side</em></strong><em>:</em></p><pre>// src/index.js<br>const endpoint = &quot;https://iamendpoint/v1/getPosts&quot;;</pre><pre>const App = () =&gt; {<br>  // call endpoint </pre><pre>  // and do pagination w/ initial data if trigger bottom<br>  return (<br>    &lt;ul&gt;<br>        {data.map({title,author}=&gt;<br>            &lt;li key={title}&gt;{author}/{title}&lt;/li&gt;)<br>        }<br>    &lt;/ul&gt;<br>  )<br>}</pre><p>把他變這樣 <strong><em>server side</em></strong><em> rendering component</em>:</p><pre>// src/index.js<br>const endpoint = &quot;https://iamendpoint/v1/getPosts&quot;;</pre><pre>const App = ({initialData={}}) =&gt; {<br>  // do pagination w/ initial data when trigger bottom<br>  return (<br>    &lt;ul&gt;<br>        {initialData.map({title,author}=&gt;<br>            &lt;li key={title}&gt;{author}/{title}&lt;/li&gt;)<br>        }<br>    &lt;/ul&gt;<br>  )<br>}</pre><pre><strong>App.getInitialData = async ({req})=&gt; {<br>   const response = await fetch(endpoint, {headers: req.headers});<br>   const initialData = await response.json();<br>   return {initialData};<br>}</strong></pre><p>Update: refer this:</p><p><a href="https://github.com/realdennis/react-ssr-reddit-meme/blob/master/src/index.js#L56-L60">realdennis/react-ssr-reddit-meme</a></p><h4>Step 2— call getInitialData() before renderToString</h4><p>啊！既然我們不想用框架，又設計了一個一個新的 method getInitialData ，這時候就在 server-side 組裝 html 前，先把他執行好後並塞進去。</p><p>通常是在 express 的 server.js，你爽的話也可以 Koa ，反正你只要能執行那串 getInitialData 就可啦。</p><p>你想更爽也可以用 Ruby Python Java … 也可，反正概念一樣只是沒有辦法同構 JS &amp; reuse code。</p><p>沒執行大概會長的像這樣<strong>（沒啥卵用的 SSR）</strong>：</p><pre>// server.js<br>import App from &#39;./src/components/App.jsx&#39;</pre><pre>router.get(&#39;/&#39;, async(req,res)=&gt;{<br>  const ReactAppHTML = ReactDOM.renderToString(&lt;App/&gt;);<br>  const html = `<br>    &lt;div id=&quot;root&quot;&gt;{ReactAppHTML}&lt;/div&gt;<br>    &lt;script <strong>src=&quot;client.js&quot;</strong>&gt;&lt;/script&gt;<br>  ` <br>  //我懶得寫 html body tag </pre><pre>  res.status(200).send(html)<br>})</pre><p>有先執行再塞進去的大概長這樣（這下有 props 了）：</p><pre>router.get(&#39;/&#39;, async(req,res)=&gt;{<br>  <strong>const {getInitialData} = App;<br>  const props = await getInitialData();<br>  const ReactAppHTML = ReactDOM.renderToString(&lt;App {...props}/&gt;)</strong></pre><pre>  //下略<br>})</pre><p>Update: refer this</p><p><a href="https://github.com/realdennis/react-ssr-reddit-meme/blob/master/server.js#L10-L12">realdennis/react-ssr-reddit-meme</a></p><h4>Step 3—hydrate 階段也要有 state</h4><p>我們都知道單純的 renderToString 射回前端，只不過是一坨沒有功能的 markup （先把水杯、殼先傳過去），所以我們會把 hydrate logic build 成一個 client.js，透過這支 .js ，在 client side 去把 React 的 event/state 掛回去。（再把水杯裝水、裝 React）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VqF5gts-LLcVHCz3" /><figcaption>Photo by <a href="https://unsplash.com/@dylu?utm_source=medium&amp;utm_medium=referral">Jacek Dylag</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>它原本長這樣：</p><pre>// client.js<br>import React from &#39;react&#39;;<br>import {hydrate} from &#39;react-dom&#39;;<br>import App from &#39;./components/App.jsx&#39;</pre><pre>hydrate(<strong>&lt;App/&gt;,</strong>document.querySelector(&#39;#root&#39;));</pre><p>啊幹 可是他這樣沒狀態啊 這樣會發生什麼事？</p><p>你的畫面會瞬間閃一下，然後在前端狀態變回空物件{}，直接踩到 pagination 又再 call 了一次 initial data fetching（如果你有<a href="https://github.com/realdennis/react-ssr-reddit-meme/blob/master/src/index.js#L11-L15">防呆</a>的話啦）。</p><p>而且你按 F12 點 console ，你會看到 React 靠北你</p><p>：<strong>幹嘞，你前後端的生的 html 長不一樣，搞毛啊？</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8EU9pcy6OPF43u6LnoqgA.gif" /><figcaption>明明 server side generate 好的東西，使用者卻又要再重打一次，在SEO/Performance audit 上看來絕對是顯著的 Cumulative Layout Shift impact。</figcaption></figure><p>問題來了？那我們在 server.js 裡面 call getInitialData 的結果（props） 要怎麼在 client-side call hydrate 的時候塞進去呢？</p><p>還記得我們剛剛不是有個地方在刻純手打的 html 嗎？</p><p><strong>我們前端仔有個最具 powerful 的小東東叫做 </strong><strong>&lt;script&gt; </strong>。</p><p>讓我們回到 server.js</p><pre>router.get(&#39;/&#39;, async(req,res)=&gt;{<br>  <strong>const {getInitialData} = App;</strong><br>  <strong>const props = await getInitialData();</strong><br>  // 這邊拿到 data 惹對吧</pre><pre>  const ReactAppHTML = ReactDOM.renderToString(<strong>&lt;App/ {...props}&gt;</strong>)</pre><pre>  const html = `<br>    &lt;script&gt;<br>      <strong>window.__my__fucking__props__=${JSON.stringify(props)};</strong><br>    &lt;/script&gt;</pre><pre>    &lt;div id=&quot;root&quot;&gt;<strong>{ReactAppHTML}</strong>&lt;/div&gt;<br>    &lt;script src=&quot;<strong>client.js</strong>&quot;&gt;&lt;/script&gt;<br>  `<br>    // again 我懶得寫 html body tag</pre><pre>    //下略<br>})</pre><p>這時候發生什麼事？我們的 client side 的 window.__my__fucking__props__ 會拿到 initial props 。</p><p>讓我們回到 hydrate 階段</p><pre>// client.js<br>import App from &#39;./src/index.jsx&#39;</pre><pre>hydrate(<br>  <strong>&lt;App {...window.</strong><strong>__my__fucking__props__}/&gt;,<br>  </strong>document.querySelector(&#39;#root&#39;)<br>);</pre><p>大功告成！前後狀態一致，讚。</p><p>更新：DEMO <a href="https://react-ssr-reddit-meme.herokuapp.com/">https://react-ssr-reddit-meme.herokuapp.com/</a> 你可以 curl 測試 SSR 的正確性已經點擊觸發 react hooks 測試 react 功能。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxl12JQoWzJdM4mNXNHC3g.gif" /><figcaption>react events / hooks testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Du5RIE0UIZ5pbdydGsy0Lg.gif" /><figcaption>curl <a href="https://react-ssr-reddit-meme.herokuapp.com/">https://react-ssr-reddit-meme.herokuapp.com/</a> testing</figcaption></figure><h4>尾聲</h4><p>幫大家總結一下，想要弄一套既有 server-side data fetching 的 SSR 其實只需要幾個步驟：</p><ol><li>在 page 組件新增一 initial 執行的 function</li><li>在 server side 渲染期間，將其預先執行，並在 renderToString 時傳入</li><li>在 markup 渲染期間，將狀態丟入 Client-side</li><li>在 hydrate 階段將狀態塞進去 react app 承先啟後</li></ol><p><strong>另外想備註幾個翻了許多文章幾乎沒被提到的點：</strong></p><ol><li>文內有提到，任何語言都可以實現 react SSR ，你爽的話也可以用 Python / Ruby 寫 service，最後在 renderToString 與 hydrate 階段把資料介接進去即可，用 JS 的好處在於同構性，reuse code 、 reuse environment。</li><li>Server-side render 的好處不只是 SEO ，當第一頁（首屏）畫面的 data fetching 跟 render 在同一台/群機器上，透過 server 做請求比較快也健康。（可以在 server side 控制 data/template cache，減去負擔）</li><li>承上，除去 SEO/Performance 以外，這類的 server-side fetch 更可以透過 forward user identical info 來做到資料個人化。簡單舉例：若 endpoint 也是我所擁有，我可以將 user cookie 傳進去，那麼即便是在 server-side 做的 request 得到個人化內容。</li><li>承上，如果你還記得之前寫的文章《<a href="https://realdennis.medium.com/polyfill-%E7%AD%96%E7%95%A5%E8%88%87-bundle-%E5%A4%A7%E5%B0%8F%E7%9A%84%E7%88%AD%E9%AC%A5-8260665b8c94">Polyfill 策略與 bundle 大小的爭鬥</a>》裡頭提過，在 server-side render 階段，我們可以動態決定要不要為使用者加載對應的 Polyfill ，更可以整合在 middleware 做更詳細的預處理。</li><li>JSON.stringify 沒辦法適用大多數的場景如 functions, regexps, dates, sets, maps，推薦使用這個專案：<a href="https://github.com/yahoo/serialize-javascript">serialize-javascript</a>。</li><li>這個 Demo 完全沒有 performance 考量，可以考慮試著走 stream pipe，但建議若要 extend usage 直接用 OSS framework ，你不會想在開發 feature 的時候修 framework 的，請相信我。</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e2063c51663" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[面對 Promise 的思考路徑]]></title>
            <link>https://realdennis.medium.com/%E9%9D%A2%E5%B0%8D-promise-%E7%9A%84%E6%80%9D%E8%80%83%E8%B7%AF%E5%BE%91-bd53461edf59?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd53461edf59</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mindgraph]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 22:57:23 GMT</pubDate>
            <atom:updated>2021-04-29T23:08:09.957Z</atom:updated>
            <content:encoded><![CDATA[<h4>Promise 是常見的面試問題，相信各位打工仔肯定是不陌生，但往往會是：用的時候覺得理所當然，成為考題時卻覺得絆手絆腳難以解釋。這邊我想用一篇文章來整理思考路徑，以讓下次碰到這類提問是有個思考模型。</h4><h4>前言（廢話）</h4><p>JavaScript 是一個非同步（異步）的語言，我們常常在解決使用者觸發的事件、Network IO 的請求、計時器觸發…之間打轉，對比其他同步語言，可以直落落的寫下來，JavaScript 仰賴的是回調函數（Callback）的幫助來分工合作。</p><p>但由於太多 callback 需要控制，往往就是會看到 callback 1 裡面塞 callback 2 來確保 order 正確，這也是俗稱的回調地獄（callback hell），而 Promise 的出現解決了這個問題。</p><p>Promise 是 ES6 的 built-in 函數，也就是說 15&#39; 年開始寫 JS 的人，多半都會直接使用這個方法來取代 callback hell 的巢狀格式，在下個版本 ES7 中，更有 based on Promise 的 async / await 方法，也就是說，學 Promise 絕對是划算至極。</p><h4>心智模型</h4><p>學習、記憶、思考總是需要有一個如同樹圖的聯想方式，在這個章節我們先站在面試官的角度思考一下：<strong>如果你要生出 Promise 的題目來考面試者</strong>，該怎麼下手呢？</p><p>我們參考 MDN 的文件，來看看 Promise 有哪些 method：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*OnGjUgSR7Z4UQQrz8UQmJQ.png" /></figure><p>我們可以看到這邊有 resolve() 、 reject() 、all()、 allSettled() 、any() 、race() 、then() 、 catch() 、finally() ，可以看到我沒有照著文檔排序，而是依照一個心中既有的分類去做排序：</p><ul><li><strong>決定 Promise 狀態（結果）</strong>的： Promise.resolve() 、 Promise.reject()</li><li><strong>決定 Promise tasks 競賽方式</strong>的： Promise.all() 、 Promise.allSettled() 、 Promise.any() 、 Promise.race()</li><li><strong>決定 Promise task(s) 後續</strong>的： Promise.then() 、 Promise.catch() 、 Promise.finally()</li></ul><p>如此我們便可以畫出一個脈絡圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcWV4U1F0vgG3XzCixr2NA.png" /></figure><h4>決定 Promise 狀態（結果） — resolve &amp; reject</h4><p>當我們在 new 一個 Promise 實例的時候，Promise 會給我們兩個決定結果的函數，大致上如下：</p><pre>const SimplePromise = new Promise((resolve,reject)=&gt;{<br>  if(somethingGood) resolve(result);<br>  if(somethingBad) reject(new Error(&#39;something bad&#39;));<br>})</pre><pre>SimplePromise.then().catch()</pre><p>值得注意的是，resolve() 與 reject() 是<strong>靜態方法</strong>，所以你爽的話也可以直接 call 這兩個方法，生成一個有 fulfilled/ rejected結果的物件：</p><pre>&gt; Promise.resolve(true);<br>&lt; Promise {&lt;fulfilled&gt;: true}<br>&gt; Promise.reject(false);<br>&lt; Promise {&lt;rejected&gt;: false}<br>X VM581:1 Uncaught (in promise) false (anonymous) @ VM581:1</pre><h4>決定 Promise tasks 競賽方式— all 、 allSettled 、 race 、 any</h4><p>當我們有多個 Promise 綁定在一起處理的時候，有兩種大宗的 scenario：</p><ol><li><strong>Order concerned (一個接著一個)</strong></li><li><strong>Asynchronous (去做各自的事)</strong></li></ol><p>針對第 1. 點，只有在兩個 Promise 之間有互相依賴的時候，才會有 order concerned 的狀況，如下：</p><pre>promiseA<br>  .then(result=&gt;PromiseBFactory(result))<br>  .then(finalResult=&gt;console.log(finalResult))</pre><p>通常這類的 case <strong>最終會集成在同個 Promise 裡頭</strong>（如將上述的函數<strong>集成為一個 independent 的 </strong><strong>PromiseAB</strong>），而內部或許會用 ES7 的 await 去實現，才不會用過度嵌套的 then chain。<strong><em>順帶一提，那種要求你用 Promise 實作 order concerned 的公司就別去了，他們需要的是一個會配置 ES7 await 的 babel 工程師。</em></strong></p><p><strong>那我們這邊提到的競賽方式，主要是針對第 2. 點，多個 tasks 競賽如下：</strong></p><pre>raceRule([Promise1,Promise2.Promise3]).then(???)</pre><p>這個 raceRule 可以有幾種 case：</p><ol><li>誰先結束誰贏 Promise.race 、Promise.any</li><li>大家一起結束 Promise.all 、 Promise.allSettled</li></ol><p>我們來逐個討論。</p><p><strong>誰先結束誰贏 —— 失敗算不算一種結束？</strong></p><ul><li>失敗算一種結束 Promise.race</li><li>只有 fulfilled 才算結束 Promise.any <em>（一個 reject 等下一個，全部 reject 進入 rejected）</em></li></ul><p><strong>大家一起結束——失敗算不算一種結束</strong></p><ul><li>失敗算一種結束 Promise.allSettled</li><li>只有 fulfilled 才算結束 Promise.all <em>（其中一個 rejected 的話會進入 catch）</em></li></ul><p>用個生活的例子舉例吧：</p><pre>假設現在有兩對情侶 A B，他們在大學校園的樹下埋下六人的合照，交往過程是一個 Promise pending ， <strong>最終結婚是 fulfill</strong> ，而<strong>分手則是是 rejected</strong>。他們約定好在以下的狀況下拆開時光膠囊：</pre><pre>1. 如果<strong>其中有一對結婚了</strong>，拆時光膠囊吧！ Promise.any([A,B])<br>2. 如果<strong>其中有人結婚或分手了</strong>，丟掉時光膠囊吧！ Promise.race([A,B])<br>3. 如果<strong>大家都結婚了</strong>，拆時光膠囊吧！ Promise.all([A,B])<br>4. 如果<strong>大家狀態確定了</strong>（分手、結婚），丟掉時光膠囊吧 Promise.allSettled([A,B])</pre><pre>最終情侶A在4年後結婚，情侶B則是在三年後就分手了，那麼以上四個case會是怎麼樣呢？</pre><p>For case 1 :</p><pre>//1. 如果其中有一對結婚了，拆時光膠囊吧！ Promise.any([A,B])<br>const A = new Promise(resolve=&gt;setTimeout(resolve,4,&#39;A&#39;));<br>const B = new Promise((_,reject)=&gt;setTimeout(reject,3,&#39;B&#39;));</pre><pre>setTimeout(()=&gt;Promise.any([A,B]).then(console.log)); <br>// A</pre><p>For case 2:</p><pre>//2. 如果其中有人結婚或分手了，丟掉時光膠囊吧！ Promise.race([A,B])<br>const A = new Promise(resolve=&gt;setTimeout(resolve,4,&#39;A&#39;));<br>const B = new Promise((_,reject)=&gt;setTimeout(reject,3,&#39;B&#39;));</pre><pre>setTimeout(()=&gt;Promise.race([A,B]).then(console.log)).catch(console.error); // Error: B</pre><pre>// B如果在五年後差分手，那麼不會走到 catch 喔！</pre><p>For case 3:</p><pre>//3. 如果大家都結婚了，拆時光膠囊吧！ Promise.all([A,B])<br>const A = new Promise(resolve=&gt;setTimeout(resolve,4,&#39;A&#39;));<br>const B = new Promise((_,reject)=&gt;setTimeout(reject,3,&#39;B&#39;));</pre><pre>setTimeout(()=&gt;Promise.all([A,B])<br>  .then(console.log)<br>  .catch(console.error)); // B </pre><pre>// B is the reject reason<br>// 儘管B在五年後差分手 一樣是導致all method失敗的reason喔！</pre><p>For case 4:</p><pre>// 4. 如果大家狀態確定了（分手、結婚），丟掉時光膠囊吧 Promise.allSettled([A,B])<br>const A = new Promise(resolve=&gt;setTimeout(resolve,4,&#39;A&#39;));<br>const B = new Promise((_,reject)=&gt;setTimeout(reject,3,&#39;B&#39;));</pre><pre>setTimeout(()=&gt;Promise.allSettled([A,B]).then(console.log)); <br>// [<br>//  { status: &#39;fulfilled&#39;, value: &#39;A&#39; },<br>//  { status: &#39;rejected&#39;, reason: &#39;B&#39; }<br>// ]</pre><p>如果是從<strong>單一/全體</strong>來看，我們可以分成：</p><ul><li>單一完成為主的 race &amp; any</li><li>全體完成為主的 all &amp; allSettled</li></ul><p>如果是從<strong>完成狀態</strong>來看，我們可以分成：</p><ul><li>成功失敗都算的 race &amp; allSettled</li><li>只有成功才算的 any &amp; all</li></ul><h4>決定競賽結果的後續回調的 — then、catch、finally</h4><ul><li>Promise 走到 fulfilled 狀態， result 傳進去 then 的 callback</li><li>Promise 走到 rejected 狀態， reason 傳進去 catch 的 callback</li><li>Promise 不論走到哪個狀態，當 then 與 catch 執行 完，接著執行 finally 的 callback</li></ul><pre>// 1. Promise fulfilled<br>Promise.resolve(&quot;I&#39;m result&quot;).then(console.log) // I&#39;m result</pre><pre>// 2. Promise rejected<br>Promise.reject(&quot;reject reason&quot;).catch(console.error) // reject reason</pre><pre>// 3. Promise finally<br>const APromise = new Promise((resolve,reject)=&gt;{<br>  // I don&#39;t know wtf will going on<br>})</pre><pre>APromise<br>  .then(result=&gt;{<br>    // Processing if APromise fulfilled<br>  })<br>  .catch(reason=&gt;{<br>    // Processing if APromise rejected<br>  })<br>  .finally(()=&gt;{<br>    // MUST DO THIS WHENEVER FULFILLED OR REJECTED<br> })</pre><p><strong>then 、 catch 、 finally 之間的關係猶如 try 、 catch 、 finally</strong></p><h4>尾聲</h4><p>透過這樣的分類方式，我們可以輕鬆的在任意的 Promise 實作考題中如魚得水（大概吧？），無論你是想從中抽考面試候選者，或是你自己在面對面試題的時候，都能輕易從 Promise 的既有方法中，找到題目想要引導的思路與本意。</p><p>有了兩個最終狀態的設定，我們也能做到一些防呆機制的 Promise 封裝，解決類似以下的問題：</p><pre>1. 由於我們在UI測試實驗中，發現使用者只願意等待2~5秒的時間在請求加載上，能否為我們設計、封裝一回傳 Promise 的高階函數 foolProofRequest ，其接受一網路請求的函數 fn 作為第一參數，一個毫秒數 n 為第二參數，其會去做非同步的網路請求，但是 n 毫秒沒有回傳就 timeout 的函數。</pre><pre>const foolProofRequest = (fn, n) =&gt; ?</pre><p>and</p><pre>2. 接續上題目，由於我們非常注重使用者交互，我們準備了三個同樣回傳格式的 endpoints A B C，能否將其設定為 A 容忍秒數為 2、B 容忍秒數為 3、C 容忍秒數為 1，且當一 endpoint 得到了回傳結果後，就將其傳入渲染函數 render 裡頭，當三個 endpoint 都失效、過期，請呼叫 exceptionHandler 函數，且在全部行為結束後，呼叫 Helloworld 函數。</pre><pre>注1：若 A endpoint 例外或是超過兩秒，我們還是會等待 B endpoint 完成。<br>注2：若 A B C endpoint 皆例外或是過期，我們</pre><pre>Promise.???([foolProofRequest(A,2000),foolProofRequest(B,3000),foolProofRequest(C,1000)])<br>  .then(???)<br>  .catch(???)<br>  .finally(???)</pre><p>大家可以想想怎麼實作它。</p><p>延伸閱讀，一些以前寫過與 Promise 有關的文章：</p><ul><li>Promise 的 then 可以一直串下去，什麼是鏈式調用？——<a href="https://realdennis.medium.com/%E5%A6%82%E4%BD%95%E5%B0%81%E8%A3%9D%E4%B8%80%E5%80%8B%E5%8F%AF%E8%A2%AB%E9%8F%88%E5%BC%8F%E8%AA%BF%E7%94%A8%E7%9A%84%E5%87%BD%E5%BC%8F%E5%BA%AB-a64ca464be32">如何封裝一個可被鏈式調用的函式庫？</a></li><li>透過 Promise 把難搞的回呼函數變成 Promise 物件吧？——<a href="https://realdennis.medium.com/%E4%B8%80%E8%B5%B7%E4%BE%86%E6%8A%8A%E7%85%A9%E4%BA%BA-xmlhttprequest-%E8%AE%8A%E6%88%90-fetch-%E6%80%8E%E9%BA%BC%E6%A8%A3-8657f2854894">一起來把煩人 XMLHttpRequest 變成 Fetch 怎麼樣？</a></li><li>只能 Callback 方式寫作的非同步函數無腦變成 Promise 好爽喔！——<a href="https://realdennis.medium.com/promisify-%E8%88%87-callbackify-%E4%BD%A0%E6%88%96%E8%A8%B1%E7%94%A8%E4%B8%8D%E5%88%B0-%E4%BD%86%E4%BA%86%E8%A7%A3%E4%B8%80%E4%B8%8B%E4%B9%9F%E7%84%A1%E5%A6%A8-193d7091c091">Promisify 與 Callbackify — 你或許用不到，但了解一下也無妨</a></li><li>Promise 好像是一個有限狀態機，那麼有辦法從零開始寫一個 Promise 的 class 嗎？——<a href="https://realdennis.medium.com/promise-%E9%A1%9E%E7%9A%84%E5%AF%A6%E4%BD%9C%E8%88%87%E9%80%90%E6%AD%A5%E8%A7%A3%E6%9E%90-4a87a4121d35">JavaScript Promise 類的實作與逐步解說</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd53461edf59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Browser 上的 ESmodule & 現代化的前端打包工具 Snowpack / Vite]]></title>
            <link>https://realdennis.medium.com/browser-%E4%B8%8A%E7%9A%84-esmodule-%E7%8F%BE%E4%BB%A3%E5%8C%96%E7%9A%84%E5%89%8D%E7%AB%AF%E6%89%93%E5%8C%85%E5%B7%A5%E5%85%B7-snowpack-vite-95b9d2beb89d?source=rss-617335840e0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/95b9d2beb89d</guid>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[snowpack]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[realdennis]]></dc:creator>
            <pubDate>Sun, 22 Nov 2020 12:45:07 GMT</pubDate>
            <atom:updated>2020-11-26T08:06:30.035Z</atom:updated>
            <content:encoded><![CDATA[<h3>Browser 上的 ESmodule &amp; 現代化的前端構建工具 Snowpack / Vite</h3><h4>瀏覽器看得懂 import / export 耶！支援程度如何？對資深前端打工仔 aka 網頁開發者來說又有什麼改變？未來的打包趨勢跟當今的 solution 又有何不同呢？</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*D_Gb3fY_W4A-DIjO" /></figure><h4>大致上談幾件事</h4><ul><li>Browser 上原生的 import / export 怎麼用、原理</li><li>Support 程度</li><li>對前端工程化影響</li><li>適用 ESM 之打包工具——Snowpack / Vite</li></ul><h4>寫在前面</h4><p>本文將會以速食般的速度，不廢話的講重點，不會加入太多前提解釋。</p><p>適合閱讀的受眾：</p><ul><li>已經了解前端工程化</li><li>了解當代打包工具功能的前端打工仔。</li></ul><p>不適合閱讀本文：</p><ul><li>（Tune 模板）<strong>只有在 HTML 嵌入過 Bootstrap/jQuery</strong></li><li>（前端新人）<strong>沒有 build 過 npm package 到瀏覽器上</strong></li><li>（來自 2008 年的時空穿越者）<strong>以為前端只能寫幾個按鈕給 User submit</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*R5zzVVtkccOqv_Qu.JPG" /></figure><h4>Browser 上的 import / export</h4><p>你熟悉的 ESModule ， import xxx from ‘ooo’ / export default ，現在可以跑在瀏覽器上，說<strong>現在</strong>其實不太精確，其規格在 ES6 就定好了。（靠北， 2015 欸！）</p><p><em>註：開發者都是傾向於寫 ESModule 的語法，再透過 Babel 這類的工具把它轉成 Node 可以看懂的 CommonJS （</em><em>require / </em><em>module.exports = {}）。</em></p><p><strong>啊怎麼用？</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*SEBPu-k3ue0PTrHF.JPG" /></figure><p>首先 HTML 上，這段要用 ESModule 的 script 必須要長這樣：</p><pre>&lt;script type=&quot;module&quot; src=&quot;js/index.js&quot;&gt;</pre><p>你的 JS 裡頭就可以用 import / export 了</p><pre>import helloworld from &#39;./helloworld.js&#39;<br>helloworld()</pre><p>而 helloworld.js 就是：</p><pre>export default ()=&gt; {<br> console.log(&quot;hello world&quot;);<br>}</pre><p>你的 static folder 大概長這樣</p><pre>├── index.html<br>└── js<br>    ├── helloworld.js<br>    └── index.js</pre><p>不相信嗎？我 Code 都寫好了，直接來 Verify 吧，沒混直接發。</p><p>啊不是，是沒 bundle 直接發。</p><ul><li><a href="https://github.com/realdennis/ESM-demo">realdennis/ESM-demo</a></li><li><a href="https://realdennis.github.io/ESM-demo/">ESModule Demo</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*Zgt16syOIFx06wy5" /></figure><h4>ESModule 的 支援度如何？</h4><p><a href="https://caniuse.com/?search=es6-module">https://caniuse.com/?search=es6-module</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McOMyWuuAAUSlNHfxdkguw.png" /></figure><p><strong>IE 就不用想了，不過號稱當代手機界的IE—Safari是支持的呢。</strong></p><p>這個支援度…好像滿猛的耶？如果不考慮 IE 這個爛東西，似乎可以朝著 ESModule 的路筆直向前了！</p><h4>ESModule 跟以往的體驗差異</h4><p>我們從上面的廢物 Demo 了解到：</p><ul><li>所有的模組都是 static 的 js file</li><li>瀏覽器會 Handle relative /absolution URL 並加載模組的過程</li></ul><p>這意味著幾件事情：</p><ul><li>Code splitting</li><li>Decrease file size</li><li>Network concurrent fetch</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNOqZzQM1x8cRIeN.png" /></figure><h4>ESmodule 對前端工程化的影響</h4><p>傳統的前端工程化（如Webpack 、 Parcel） 等等的 bundler 都是將整個code 、 dependency 塞到單一一隻 JS File 載入。</p><p><em>註：儘管可以透過宣告方式做 Code Splitting 、 lazy loading，但無論是前者可以被 ESModule 的分拆解決，或是後者可以透過原生的 </em><em>import() 解決。</em></p><p>這也意味著，當你選擇了 ESmodule 作為開發，你對於 build time 需要去處理的 Effort <strong>大大降低</strong>，再也不需要雜亂的 Bundler 配置、設定 Entry file 等等的，只要透過 &lt;script type=module&gt; 就可以進入具 module dependency 的 JS code。</p><p><strong>但實際上有這麼理想嗎？ node_modules 的 packages / CSS的預處理 / babel transform / typescript …工程化還有這麼多件事，難道只能繼續捆綁在 Webpack 了？</strong></p><p>我們仍然需要有 build tool 在 build time 時幫我們：</p><ul><li>把 package dependency 放到對應的 static folder裡頭</li><li>做一些預處理的動作（包括 .ts/.jsx /.scss /.sass / …）</li></ul><h4>Snowpack — modern bundler</h4><p>Snowpack is a <strong>modern frontend build tool</strong> for faster web development. It replaces heavier, <strong>more complex bundlers like webpack or Parcel in your development workflow</strong>.</p><p>Snowpack <strong>leverages JavaScript’s native module system (</strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import"><strong>known as ESM</strong></a><strong>) to create a first-of-its-kind build system that never builds the same file twice.</strong> Snowpack pushes changes instantly to the browser, saving you hours of development time traditionally spent waiting around for your bundler.</p><p>以上在 Build time 需要完成的事情 Snowpack 都可以透過其原始的功能或者對應的 Plugin （你也可以想象成 Loader）去做掉。</p><p>有趣的是他們解決 node_modules 的方法，如果你試著透過 snowpack 來 build 你的 index.js 如下：</p><pre>// src/index.js</pre><pre>// The below three is from node_modules<br>import rQUI from &#39;rQUI&#39;;<br>import carousel from &#39;rQUI.carousel&#39;;<br>import animation from &#39;rQUI.animation&#39;;</pre><pre>// The below one is what you create and import<br>import elements from &#39;./elements.js&#39;; </pre><p>最終 build 出來的 _dist_/index.js 會是</p><pre>// _dist_/index.js<br>import rQUI from &#39;/web_modules/rQUI/index.js&#39;;<br>import carousel from &#39;/web_modules/rQUI.carousle/index.js&#39;;<br>import animation from &#39;/web_modules/rQUI.animation/index.js&#39;;</pre><p>你的 public folder 會是這樣的 file structure：</p><pre>├── _dist_<br>│   └── js<br>│       ├── elements.js<br>│       └── index.js<br>├── index.html<br>└── web_modules<br>    ├── rQUI<br>    │   └── index.js<br>    ├── rQUI.carousel<br>    │   └── index.js<br>    └── rQUI.a<br>        └── index.js</pre><p>屆時這些東西會一路從 public folder server 到 web 上，而 Browser 在吃到 ESModule 後會自動發起網路請求，並且把這些東西 collect 回來 as module。</p><h4>另外一個一樣風格的 build tool —Vite</h4><p>無獨有偶也是走 ESM 形式的 build tool，雖不熟悉，但我剛 init 了一個來看看，一樣的方式，我們透過 source/network tab 可以發現是相似的 file structure：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*U05jVEiiH8URq1R2KfLKnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*D7okH9LkCNMqW1THk9oZ0g.png" /></figure><h4>後記</h4><p>大型網站其實很早就有拆分 JavaScript 的邏輯，包括早期的 CDN，以及 Webpack 的 code splitting，總是先有需求，才有解法，最終變成規格。如同React &amp; Vue 之於 Web Components， ESmodule 的出現的確是一大救贖，並且搭配良好的 HTTP Server tuning，可以達到非常優秀的頁面載入速度 / 效能。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95b9d2beb89d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>