Friday, July 13, 2018

JavaScript Async/Await Reminder

Overview 

C# and JavaScript async/await provide the same feature dealing with asynchronous calls.
But the details are not the same.

Here is an article that talk about it
Comparing asynchronous patterns between C# and JavaScript

Code Sample

Here is a sample in NodeJs v 9.2, that show case why async/await is cleaner than nested Promises.
But it is important to understand what really happen behind the scene. See my comments.
/*
    Code sample based from 
        JavaScript ES 2017: Learn Async/Await by Example
        Brandon Morelli
        https://codeburst.io/javascript-es-2017-learn-async-await-by-example-48acc58bad65
*/

/* Nested asynchronous function with Promises */

function doubleAfter2Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => { resolve(x * 2); }, 1000);
    });
}
    
function addPromise(x){
    return new Promise(resolve => {
        doubleAfter2Seconds(10).then((a) => {
            doubleAfter2Seconds(20).then((b) => {
                doubleAfter2Seconds(30).then((c) => {
                    resolve(x + a + b + c);
                })
            })
        })
    });
}

console.log(`starting big async calculation with Promise`);

addPromise(5).then( (result) => {
    console.log(`big async calculation result:${result}`);
});


/* Nested asynchronous function with async/await */

console.log(`starting big async calculation async/await`);

/*
    The function addAsync does not return the result of the expression: x + a + b + c,
    as the code imply.

    Because the function is marked with the word async, the function
    really return a Promise.

    The line `return x + a + b + c;` will be executed if the promise succeed and the 
    value will be passed as the parameter of the method resolve().
*/
async function addAsync(x) {
    
    const a = await doubleAfter2Seconds(10); // Shortcut syntax to avoid to attach a 
                                             // then() and store the resolved value 
                                             // of the Promise in the variable a
    const b = await doubleAfter2Seconds(20);
    const c = await doubleAfter2Seconds(30);
    return x + a + b + c;
};

async function main() {

    // Long syntax to call an async method using a then().
    addAsync(5).then(
        (result) => {  /* result contains x + a + b + c */
            console.log(`big async calculation async/await result:${result}`);
        }
    );

    // Shortcut syntax to avoid to attach a then()
    const r = await addAsync(5);
    console.log(`big async calculation async/await r:${r}`);
}

main();


Thursday, July 5, 2018

JavaScript Promise Reminder

console.log(`Starting...`);

let success = !true;

const promise = new Promise(function(resolve, reject) {
    setTimeout( () => {
        if (success) 
            resolve("worked");
        else
            reject("failed"); // reject(new Error("failed"));
    }, 1000);
});

console.log(`Async operation in progress...`);

let anotherPromise = promise.then( // then() or catch() return a new promise.
    (result) => {
        console.log(`Then 0 ${result}`);
    }
).catch(
    (err) => {
        console.log(`Catch 0 ${err}`);
    }
);

console.log(`promise === rt: ${promise === anotherPromise}`);

anotherPromise.then(
    (result) => {
        console.log('Then 1');
    }
).catch(
    (err) => {
        console.log(`Catch 1 ${err}`);
    }
);

Result:

With the success variable being false the first promise (promise) fail, but the second one (anotherPromise) succeed.
Pay attention to the fact that the variable promise and anotherPromise are not referencing the same Promise instance.

Starting...
Async operation in progress...
promise === rt: false
Catch 0 failed
Then 1

Friday, June 15, 2018

git command line helper

Overview 

git command line are difficult to remember for somebody used to Visual Source Safe, Star Team or TFS. But these days you do not have the choice. I came up with this PowerShell Script I called pgit.ps1 that translate command I can remember into git command.

Source: pgit.ps1

PS C:\>pgit list [branch, url, tag, history, merge-history]
PS C:\>pgit create branch branchName
PS C:\>pgit switch branch branchName
PS C:\>pgit delete branch branchName
PS C:\>pgit push branch branchName
PS C:\>pgit rename branch oldBranchName newBranchName
PS C:\>pgit push branch branchName # push branch to the origin server
PS C:\>pgit status
PS C:\>pgit commit # will automatically stage the all the modified files and commit
PS C:\>pgit commit -m "message" # will automatically stage the all the modified files and commit
PS C:\>pgit undo [unstaged, unstaged-staged, last-commited, -untracked-file]

AT28C16 EEPROM Programmer

Overview


The old AT28C16 EEPROM is a 2K EEPROM with 2 parallel buses:
  • One 8 bits data bus 
  • One 12 bits address bus
It is therefore easier to control without software than a modern EEPROM or FLASH chip that require one serial bus.


With a 8 bit counter plugged into the EEPROM address bus, we can select the first 256 addresses and output the programmed 256 values (each 8 bits) at the speed of the clock. 

The programmed EEPROM can also be used as a memory containing some assembly code to execute, in case you want to design your own 4 or 8 bit processor.

It is also an easy way to manage a 2 digit counter display using 2 7-segment displays, see videos by Ben Eater
Following the video I build a first programmer with an Arduino Nano and 2 shift registers to add an extra 8 GPIOs.


I would suggest to use an Arduino MEGA to control directly the 8 data bit bus and 12 address bit bus,
plus the Read/Write pin and Enable pin, for a total of 22 GPIOs needed.

Here is a second version with a dedicated board (schematic, board).



Code

Here is the main file using an Arduino Mega.


/*
 AT28C16 EEPROM Programmer 
 (C) Frederic Torres 2018

 based on `Build an Arduino EEPROM programmer`
 By Ben Eater
 https://www.youtube.com/watch?v=K88pgWhEb1M

 https://github.com/beneater/eeprom-programmer

*/
#include 
#include "EEPROM_Programmer.h"

#define APP_TITLE  "AT28C16 EEPROM Programmer Application"

#define ON_BOARD_LED 13
Led _onBoardLed(ON_BOARD_LED);
EEPROM_Programmer ep;

#define MAX_ADDR 16

void WriteEEPROM() {
 Board.Trace("About to Write EEPROM Sequence");
 delay(1000 * 1);
 Board.Trace("Writing EEPROM Sequence...");
 int baseValue = 1;

 for (int addr = 0; addr < MAX_ADDR; addr++) {

  ep.SetAddressBus8bits(addr);
  int val = addr;
  if (addr % 2 == 0) {
   val = 6;
  }
  else {
   val = 14;
  }
  
  ep.SetDataBusWriteData(val);
  Board.Trace(ep.GetStatus());
  Board.Trace("About to initiate the write op");
  delay(100);
  ep.InitiateWriteByteOperation();
  delay(100);
 }
 Board.Trace("Write EEPROM Sequence Done");
 Board.Trace("");
}

void ReadEEPROM() {
 Board.Trace("About to Read EEPROM Sequence");
 delay(1000 * 2);
 Board.Trace("Reading EEPROM Sequence...");
 int baseValue = 1;

 for (int addr = 0; addr < MAX_ADDR; addr++) {

  ep.SetAddressBus8bits(addr);  
  ep.GetDataBusReadData();
  Board.Trace(ep.GetStatus());
  delay(150);
 }
 Board.Trace("Read EEPROM Sequence Done");
 Board.Trace("");
}

void setup() {
 Board.SetPinMode(ON_BOARD_LED, OUTPUT);
 _onBoardLed.SetBlinkMode(250);

 Board.InitializeComputerCommunication(115200, APP_TITLE);
 Board.Trace("Initializing...");
 ep.Init();

 // WriteEEPROM();
 
}

void loop() {
 ReadEEPROM();
}




Thursday, June 7, 2018

JavaScript For Of Loop

Though the new JavaScript for/of loop construct is a nice syntactic sugar and similar to the foreach loop find in C#. It is worth noting that the behind the scene the implementation is based on an iterator.

eslint has even a rule to not let you use it.

error iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations  no-restricted-syntax

const list = [1,2,3];

for(let i=0; i < list.length; i++) { // Old syntax
  console.log(list[i]);
}

for(let i of list) { // New syntax
  console.log(i);
}
Transpiled with BabelJS.io  [Link]

"use strict";

var list = [1, 2, 3];
for (var i = 0; i < list.length; i++) {
  console.log(list[i]);
}



var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var _i = _step.value;

    console.log(_i);
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

Thursday, May 17, 2018

How to create and register a React redux middleware?

Overview


This post is just a reminder how to create and register a custom redux middleware.

Redux middleware: definition.

The middleware class

const middleware = function f1(store) { 

    return function f2(next) {
        
        return function f3(action) {
        
            // Do nothing but trace the action 
            console.log(`MIDDLEWARE> action:${JSON.stringify(action)}`)
            return next(action);
        } 
    }
}

export default middleware ;

The store creation and middleware registration

import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunkMiddleware  from 'redux-thunk';

import counterReducer   from './counter/counterReducer';

import middleware   from './middleware';

const rootReducer = combineReducers({
    counter : counterReducer,
});

const appliedMiddleware = applyMiddleware(thunkMiddleware, middleware);
const store             = createStore(rootReducer, {}, appliedMiddleware);

store.subscribe(function() {
    //console.log('STORE SUBSCRIBED ');
} );

export default store;

Friday, May 4, 2018

Redux Workflow - Summary

Overview


A blog post to gather my understanding of Redux (redux.js.org/).
Another good explanation can be found at Redux explained.

On button click calling synchronous action

  • The ButtonClickAction() method is called by the onClick attribute of a button and return the action:
    { type :‘BUTTON_CLICK_ACTION’ }
  • Because the action return an object it is automatically dispatched.
  • The dispatching trigger all registered reducers to be called.
  • The dispatching trigger all registered mapStateToProps() to be called. The global state is pass to each mapStateToProps() call. mapStateToProps() return the list of props for its component.
    • If the call return a different result from the previous call, a call to Component.render() will be executed

Summary

  • OnClick
  • Action get dispatched
  • Reducers
  • mapStateToProps
  • Component.render() if needed


On button click calling an asynchronous action

  • Asynchronous action are typically an HTTP call.
  • The Asynchronous action must be a function returning a return function(dispatch) {};
  • The internal function must dispatch 2 synchronous actions, for example requestStartedAction() at first and requestReceivedAction(data) when the data is received, as described below.

//
export function fetchAction(city) {

    return function(dispatch) {

        dispatch(requestStartedAction());

        axios.get(url, config).then(function(data) { 

            dispatch(requestReceivedAction(data));
        });
    }
}