2019年12月8日 星期日

JavaScript: Async Functions Tips

Welcome file

How to Avoid Being Sequential

Case 1

async function series() {  
 await wait(500); // Wait 500ms…  
 await wait(500); // …then wait another 500ms.  
 return "done!";
}
It takes 1000ms to complete.
async function parallel() {  
 const wait1 = wait(500); // Start a 500ms timer asynchronously…  
 const wait2 = wait(500); // …meaning this timer happens in parallel.  
 await wait1; // Wait 500ms for the first timer…  
 await wait2; // …by which time this timer has already finished.  
 return "done!";
}
It takes 500ms to complete, both “waits” happen at the same time.

Case 2

Original Promise Pattern

function logInOrder(urls) {  
 // fetch all the URLs  
 const textPromises = urls.map(url => {    
  return fetch(url).then(response => response.text());  
 });  

 // log them in order  
 textPromises.reduce((chain, textPromise) => {    
  return chain.then(() => textPromise)      
   .then(text => console.log(text));  
 }, Promise.resolve());
}

Modify into Async Function Pattern

👎 Too sequential
async function logInOrder(urls) {  
 for (const url of urls) {    
  const response = await fetch(url);    
  console.log(await response.text());  
 }
}
Second fetch doesn’t begin until my first fetch has been fully read, and so on. This is much slower than the promises example that performs the fetches in parallel.

👍 Nice and parallel
async function logInOrder(urls) {  
 // fetch all the URLs in parallel  
 const textPromises = urls.map(async url => {    
  const response = await fetch(url);    
  return response.text();  
 });
   
 // log them in sequence  
 for (const textPromise of textPromises) {    
  console.log(await textPromise);  
 }
}
The URLs is now fetched and read in parallel.

2019年4月2日 星期二

React: Refs


  • Gives access to a single DOM element
  • Create refs in the constructor, assign them to instance variables, then pass to a particular JSX elements as props.

Redux: Thunk

What's a thunk?

Thunk廣泛指的是: 延後執行的wrapper。

// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2;

// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 2;

Thunk in Redux:

在Redux中的Thunk應用則是指"延後執行Dispatch"。

Thunk middleware 會幫助dispatch async action, 等待action 執行完畢後再 dispatch 內容至store,達到非同步。

這個dispatch 的內容並非帶值的 action,而是一個async function,執行完畢前皆未有值;執行完畢後,此async function 將另外寫一個dispatch,自行再次dispatch至store (這次的dispatch就如同一般的同步disptch function一樣)。

2019年3月31日 星期日

React: Get URL from prop

In class extends React.Component , "this.props.match.params.xxx".
xxx is defined in Router tag.

React: Switch

Usage: To route for only one component in the Switch tag.




import { Router, Route, Switch } from 'react-router-dom';

...

<Router history={history}>
  <div>
    <Header />
    <Switch>
      <Route path="/" exact component={StreamList} />
      <Route path="/streams/new" exact component={StreamCreate} />
      <Route path="/streams/edit/:id" exact component={StreamEdit} />
      <Route path="/streams/delete/:id" exact component={StreamDelete} />
      <Route path="/streams/:id" exact component={StreamShow} />
    </Switch>
  </div>
</Router>


VS Code Environment

Extensions:

  • Insert semicolon : In shortcut, set insert "ctrl + ;", set insert with new line "shift + ctrl + ;"
  • Auto Close Tag

Preference:

  • Format on save

2019年3月28日 星期四

React: Portal

Usage

A normal react component tree normally looks like this:

And due to this cluster pattern, the bottom UI components' styling got influenced by their parents components.

To solve this restriction, React portal helps us to achieve this: 
So we could have an independent root element to do the "document.querySelector" that we can build another component tree under it without been influenced by the main branch or component tree.

Tips:

  • stopPropagation: prevent the event to bubble up to parent elements

1
2
3
4
5
6
7
<div onClick={props.onDismiss} className="ui dimmer modals visible active">
      <div onClick={e => e.stopPropagation()} className="ui standard modal visible active">
        <div className="header">{props.title}</div>
        <div className="content">{props.content}</div>
        <div className="actions">{props.actions}</div>
      </div>
</div>

  • React.Fragment: Blank HoC to wrap elements without side effect on styling 

1
2
3
4
<React.Fragment>
        <button className="ui button negative">Delete</button>
        <button className="ui button">Cancel</button>
</React.Fragment>

<...>

2019年3月6日 星期三

Book list 2019

Web development

Back-end:

  • ASP.NET Core 2 Fundamentals - Onur Gumus (3.5★)
    • Comment: It's a quick guide for dotNet Core MVC  Web App development. Slightly covered the works of M,V,C and DB. It's a good material for a quick start of web app development, yet the examples are relatively simple. 


Front-end:


  • O'Reilly: Learning React (4.5★)
    • Comment: This book might be a bit hard for people have not play around any web front-end framework before, and I personally read it back and forward for 4~5 times till I gradually started to get some concept and design philosophy. But when it comes to on hand project practice, the official doc might be better than this book.

Computer Science

Design Pattern:


  • 大話設計模式 - (Ongoing)


Software Project Management:

  • The Mythical Man-Month - 人月神話 (Ongoing)

Hobbies 

Tech:

  • The Fuzzy and the Techie - 書呆與阿宅 (Ongoing)

Self Development:

  • Do Less, Get More - 你只要做好一件事就夠了 (Ongoing)
  • The Long View - 人生的長尾效應 (Ongoing)

Git: How to clone only part of the repo (specific directory)

 https://stackoverflow.com/a/60729017/5721873