2020年9月30日 星期三

JavaScript: What is 'this'?

  • 宣告的位置不重要,重要的是呼叫的方法
  • https://zhuanlan.zhihu.com/p/23804247


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一樣)。

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

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