Tuesday, March 1, 2016

A possible way out of promise hell

I recently have been getting into promises (ie: nodejs, javascript type promises - see the Promise/A+ spec.)
I was reading several articles on this beast and found an exceptionally helpful one in the post entitled "We have a problem with promises" here.
Something told me that this could be explained better.
I believe I have found one possible better explanation.

The confusing thing about promises isn't the syntax but the very important side effects of each function involved.  What a function returns or does effects a promise dramatically.  This is because promises work entirely by side effects.
If we make the types clear, the code becomes much more understandable I think.

So lets set up some hungarian-like conventions for naming our functions and parameters and return values:

Type Prefixes:
p_     a promise
pfn_   a function that returns a promise (a promise generator)
fn_    a function that does not return a value
cbfn_  a commonJS callback that takes (fn_err, fn_success)
apcbfn_ an asynchronous promise callback function that takes (fn_resolve, fn_reject).
v_     a value (not a promise or a function)
vfn_   a function that returns a non-promise, non-function value
tfn_   a function that may throw an error
afn_   an asynchronous function that does not take a cbfn_ (does not return and throws are lost).
ajsfn_ an asynchronous commonJS function that takes a cbfn_ function (does not return and throws are lost).
resolve - a function that is called when a promise is successfully resolved with the value of the promise. Whatever value it returns becomes the value of the promise that called it.
reject -  a function that is called when a promise fails to accomplish its purpose and is called with an error value. Its return value (if any) is ignored by the promise  that called it.
Combine these to say that the value or function may be any of the types specified (if you want to get complicated).
In the "We have a problem with promises" post the author gives a little quiz of code for the reader to understand:
doSomething().then(function () {
  return doSomethingElse();
});

doSomething().then(function () {
  doSomethingElse();
});

doSomething().then(doSomethingElse());

doSomething().then(doSomethingElse);
So lets look at the first one with type prefixes added for the cases we want to study.
pfn_doSomething().then(function pfn_resolve() {
  return pfn_doSomethingElse();
});
What's happening here has several possibilities depending on what each promise ends up doing.
First lets recall how we create a promise:
var p_new = new Promise(apcbfn(pfn_vfn_resolve, fn_reject));
This is really the mother of all promise generators and once this line is run apcbfn() is instantly called.
Realize that apcbfn() is an asynchronous function and thus will never return and any throws it may do will be lost because it runs in a different call stack - except that within a promise, those throws will be caught by a closure and result in a call to fn_reject.  The only way this promise can be rejected or resolved is for one of it's callback functions to be called by the asynchronous function or for it to throw and exception.  Note that if the apcbfn() never calls either of its callback functions and never throws an exception, the promise is powerless to ever be resolved or rejected.
Once the promise is resolved (ie vfn_resolve() is called - if that is the case) its .then() function is called.  If it is rejected, the .then() function is never called - but if the promise has a .catch() function - that will be called on rejection.
Another thing to remember is that promises bubble up.  That means that each .then() in a chain is actually a nesting of .then() functions with the result of the inner .then() being passed up the chain.
This is because a resolved promise holds a value which can be returned from its resolve function. This is how promises can be nested - but the resolve function MUST return a value for this to work.
pfn_doSomething().then(function fn_resolve() {
  return pfn_doSomethingElse();
});
So above we have a function that returns a promise (pfn_doSomething).  That function, once it creates the promise instantly starts running the promise's apcbfn() function which never returns but because it is inside a promise will have any exceptions caught and passed on to the promise's reject function and thus its .catch() function as well.
The .then() function of pfn_doSomething() will be called only if that promise resolves successfully.
pfn_doSomethingElse() is also a promise generator which is only called upon successful resolution of pfn_doSomething() and once it is called it's corresponding internal apcbfn() function is called - which never returns either but will eventually call its reject or resolve function.  IF the resolve function returns a value, then the pfn_doSomethingElse() get's that value and returns it via fn_resolve() to pfn_doSomething() which will inherit that value internally but not call its fn_resolve() function because it already did before calling the .then() function and promises only call their fn_resolve() functions once by contract.
The reason the quiz given in the "We have a problem with promises" post can be difficult is because we don't know the actual fn_resolve(), fn_reject() and internals of apcbfn() for all the promises mentioned.  In fact, in the syntax of the original quiz, we don't even know what kind of functions the doSomething... functions are.  Here I am assuming they are promise generators and note that explicitly with the prefixes but I also must assume that the apcbfn() functions don't throw errors and that the fn_resolve() functions return values and don't throw errors either.
I think if a newbe to promises like me uses these prefixes in their first coding attempts, things will be easier to follow.
Perhaps this could become a convention to help us all read promise code better.

Sunday, May 17, 2015

Windows is fading into history yet...


When I made a visit to some old Microsoft friends of mine a month or so ago, they told me forget Windows - it's history.  And it probably is.
Microsoft, the company that put its software on every desktop in the world shot itself in the foot just too many times.
I recently was in town trying to print up some postcards done in Mail Merge with Word.  The margins weren't quite right and Staples didn't have any workstations for me to fix it.  I had to take it to another place that fixed PCs and pay $27 to tweak it and have it converted to PDF format.  Why PDF?  The person at the computer place explained that Microsoft's many versions of Word were not compatible with themselves and thus PDF format became the preferred printing format.
Outstanding!

Here's how I would save Windows if I were the VP in charge:

  1. Separate the Kernel from the rest and sell it as a rock solid separate product.
  2. Sell the GUI and Shell separately and create versions that work on the Kernel that work like NT2000, XP, Win7 and Win8 and let the user chose which shell they want to install.
  3. Make the shells open source and let others make whatever shells they want to for the OS.
  4. Let all non-essential services and features be installed optionally.
  5. Let the user chose between a standard stupid user configuration and a savvy user configuration that doesn't hamper the user from accessing and seeing everything as it really is.
  6. Create a smart interactive website that documents the registry and all other aspects of Windows with the ability for users to contribute and improve it - kinda like a wiki for windows.
  7. Improve setups to install, uninstall and move/relocate each feature or app.
  8. All services or other components that store state should be able to write their state to a file and read it back in - this allows easy state comparisons for research/troubleshooting and helps make components portable.
I don't know if this would save things or not but it would give users much more choices and power to effect changes for themselves instead of this monolithic mess that keeps changing on us.

2 C

Sunday, May 11, 2014

Gotta love it

I am/was a UI developer.  My work forces me to think about the end user all the time.  So here's another lame Microsoft example from Windows Live Mail which I just had to rant about.
Is this lame or what?
Which Server?  What Certificate?  What does CN mean to an end-user?  What was the passed in value?
This is just a lazy dialog where the programmer just didn't want to take the time to locate the pertinent information to tell the user.  I can appreciate that sometimes, when an error happens, it is so far away from where the data is that it can take some real work to get that information to the user - but without it, the UI is kinda useless.
I keep getting these and I use 5 accounts on WLM so it's been difficult for me to fathom what is really the problem.

Rant Done.

Saturday, March 15, 2014

All glyphs for UTF-8

I spent some time producing a better glyph page for the UTF-8 codepage - just for kicks.  Maybe somebody can use it.

Go Here

Saturday, December 14, 2013

MSIE 11 - isnt

I got pretty upset when I was trying to figure out how to identify IE 11 from other browsers when trying to get a simple sound playing function to work on all browsers.
It turns out IE has decided in version 11 to lie about itself.
The userAgent string for IE11 no longer has the string "MSIE" in it - which has been there since it began.
Luckily, I did find a solution here.
But just because the magic of regular expressions comes to save the day doesn't excuse Microsoft for once again throwing yet another monkey-wrench into programming by lying.
The userAgent string has the express purpose of identifying to code what browser and version is running.  If you are viewing this on IE11 (which I am writing it on) and you select the help\about menu option, you will see it says "Internet Explorer 11" followed by a precise build number.
If you print the navigator.userAgent string you will find:

Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko

Now where do you see either "Internet Explorer/IE" or "version 11" in that string?  Well you can tell its MSIE because it says "Trident" and you can tell it's version 11 because it says "7.0" - simple right?
Most likely this change was decided upon because Microsoft has been trying to better emulate Firefox and this userAgent string is so much like a Firefox userAgent string as to fool existing code.
But IE is not Firefox and I know for a fact that there are still lots of differences between IE11 and the latest Firefix browser.
It is the short-cut to save time so that a million other developers, like yours truly, can spend hours searching for or inventing a solution.  It's the kind of lazy logic that makes the world just a little bit worse.
Thank you Microsoft-bozo, whoever you are, that made this LAME decision.

Sandy

PS: Ah Microsoft receives the righteous consequence of their stupidity:
Google is not happy with IE11!

The browser we detected is unsupported and may result in unexpected behavior.
Please choose from our list of
supported browsers for the best experience.

Sunday, November 10, 2013

A review of the Eric P. Dollard video FOUR QUADRANT REPRESENTATION OF ELECTRICITY.

I just completed viewing a video of Eric P. Dollard entitled FOUR QUADRANT REPRESENTATION OF ELECTRICITY which I purchased from here.
I purchased this because I like Eric personally and I wanted to support him and because I didn't think I would have the time to get through the book.
Unfortunately, after finishing the video, I am sorely disappointed.
What this video should be titled is BASIC AC ELECTRICAL AND MOTOR THEORY USING A 4 PHASE REPRESENTATION.
The only thing in the entire video that I didn't learn at BEEP and A school in the US Navy is a minor mathematical innovation that lets you express all four quadrants of an AC wave symmetrically.  (ie introducing a +j and -j coordinate space)
Unfortunately Dollard never develops the math or subject beyond basic AC theory applications.
Dollard is always fun to listen to because he has practical experience, deep theoretical and historical knowledge and tons of interesting experiences and anecdotes to relate.  This video is no exception, I was very entertained by his anecdotes and historical references.
The quality of the video production is atrocious and shows a typical short-sighted methodology to maximize profit and minimize work.
Eric is invited to talk at a Bedini-Lindeman conference and it is recorded with a very cheap camera and microphone system.  It is then run though a cheap (freeware most likely) video editing system and reduced down to minimum quality and file size (leaving numerous and annoying compression artifacts in the video) with still shots of Eric's diagrams taken from the projector image and photos overlayed onto the video at appropriate points.  This results in blurred images and diagrams you can't read, long sections of video where Dollard is looking off to the side at the projection screen where the images are and most likely were shot from (you can see the photo flashes going off during the talk).  All the video captures of Dollard pointing out parts of diagrams using a white light pen result in a pointer image that can barely be seen on the video.
Content is also disappointing because Eric tends to favor questions and interruptions from the audience pulling him off track.  Dollard actually openly says in the video that he had to leave 90% of the theory out of the talk - he just didn't have time to cover it. 
The Dollard lecture was clearly done before the book was completed and so Dollard speaks from scattered notes.

The real disappointment is that I paid $27 for this video that is below the quality found on most instructional videos free on u-tube which the selling webpage says is
"guaranteed to meet even your highest expectations.
P.P.S. Remember, you're not risking a single penny since it is 100% guaranteed!"

 

I shall be asking for my money back soon.  Perhaps I can talk them into giving me the book rather than my money back.  I can then review that for you as well here before you have to risk your cash to find out if it is worth the price.

------ 
In general, I have found disappointment to follow almost everything I have done with the Bedini-Lindeman group.  A consistent lack of professional care in production, organization and dissemination of knowledge along the lines of alternative energy topics and consistently overpriced.
I would not go so far as to say these guys are trying to rip people off.  However, these guys are trying to make a living off of the technology before it is ready and thus I think are forced into cutting corners that a professional would not.
 
How I would do a Dollard video:
  • Get Eric to get all his images and photos into a PowerPoint form.
  • Use a good PC recording tool such as SnagIt ($35) to sit down at a PC with a good mike and give his talk in a quiet room uninterrupted using his power point images without interruption.
  • Edit this down to remove mistakes and silence.
  • Create a 1080p version of the presentation.
  • Break the talk down into sections and put an index with timestamps at the front of the video.
  • THEN sell that!
I'll let you know how the book goes if I can get it exchanged for the video.
 
Sandy
------ LATER -----
I asked for my $ back which had to go to Peter Lindeman, the man behind the sale of this lame video:

Sent: Sunday, November 10, 2013 10:54 AM
Subject: Request exchange on Four-Quadrant Representation of Electricity Video
 
I would like to propose an exchange of the video I recently purchased from http://fourquadranttheory.com/ for the book version.  (Rather than a refund)
Here is a review I have just published of the video which I think should explain my disappointment.
 
I would be happy to discuss with you ways to improve your products and might even be able to do services for you for a fee.
I had offered assistance to the Bedini crew years ago when I had published a review if one of their first conferences here.
Apparently I am not trusted due to actually being interested in helping them yet a relative stranger to them.
 
I have a friend who is a professional video editor and can do a much better job for you on videos as well – both recording and production.
 
I really do mean to be helpful to you but my consistent disappointments have caused most of my feedback to be negative.
 
Sandy Staab
Fellow Free Energy Advocate
 
To which he responded:
Dear Sanford,

Sorry you didn't like the film.  Your only recourse is to go back to Clickbank and get a refund.  There are no exchanges.  If you do get a refund for the film, please DON'T buy the book.  I assume you can find things to complain about in it, and since it covers the same material, you won't learn anything new from it anyway.

The film is a LIVE presentation to the conference audience.  The promotional materials make that quite plain.  The root camera file is cut in true HD and is over 38GB in size.  There were a few problems with the radio mics in the room, which our camera people were taking the feed from.  The file reduction to a downloadable size introduced some interlacing problems due to the MAC conversion to PC formats.  Beyond that, all of your criticisms represent your personal preference.

The purpose of the film is to make Eric's lecture, exactly as it happened, available to his students, followers and supporters.  We were specifically asked to leave it "uncut", which we did.

Your closing statement is quite telling.  The truth is, if you REALLY meant to be helpful, you would have found a way!

Regards,
Peter

To which I responded:
On 11/10/2013 9:03 PM, Sanford Staab (GMail) wrote:  
Can you tell me how much of my purchase price goes to Eric Dollard?  I’d be happy to leave you with your money should I know that I at least helped Eric with my purchase.
 
To which he responded: 
Sanford,

The financial arrangements between Eric and his publisher are confidential.  Eric is pleased with the arrangement.  You should not expect to have this sort of information shared with you, as you are not a party to the contract.

Peter

To which I responded:
 
Ok.  I would just like to know if my purchase is helping Eric.  Sounds like it is.
 
------
 
After some searching I found a much better video (I think) on the very same subject (where Eric reads from his book/notes) along with the full text of Sir Edmond Whittaker's work for FREE:
 
It is sad that people who should know how to disseminate critical knowledge instead chose to make money off of the ignorance of others and pretend to disseminate that knowledge while at the same time hiding that knowledge.

 
 
 

Wednesday, October 30, 2013

Javascript OOpseseses

Yes, well I am confessing that I enjoy working with JavaScript for much the same reasons as Mr. Douglas Crockford does.  I was attempting to do a little OO coding, trying to basically specify an interface with a base class and inheriting from that class for various implementations of the interface.
This blog I found was quite helpful to me but still vague in how to properly use it.
So here is some short code I made up that convinced me of the right way to do inheritance.
<!DOCTYPE html>
<html>
<head>
  <title>Playing with OO javascript</title>
<script type="text/javascript">

// see http://javascript.crockford.com/prototypal.html
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
// Usage:newObject = Object.create(oldObject);

function createParentClassInstance() {
    var o = {};
    o.item1 = 'Parent says: hi.';
    o.item2 = 'I\'m the parent';
    return o;
}

function createChildClassInstance() {
    var o = Object.create(createParentClassInstance());
    o.item2 = 'I\'m the child';
    o.item3 = 'Child says hi.';
    return o;
}

function out(s) {
    document.body.innerHTML += s;
}

function PageLoad() {
    var parentInstance = createParentClassInstance();
    var childInstance1 = createChildClassInstance();
    out(parentInstance.item1 + '<br>');
    out(parentInstance.item2 + '<br>');
    out(parentInstance.item3 + '<br><br>');
    out(childInstance1.item1 + '<br>');
    out(childInstance1.item2 + '<br>');
    out(childInstance1.item3 + '<br><br>');
}
</script>
</head>
<body onload="PageLoad();">
</body>
</html>
Note how we hide the definition of the objects within a clearly defined constructor function.  Inheritance is controlled by the class factory so things become clear what they mean and its not easy to just throw objects together in random inheritance trees.
If would also seem that multiple inheritance could be done this way by simply cascading the instance creation functions to make a multi-generational inheritance structure.
I am hoping that Dr. Crockford will have a chance to comment on this blog and correct me if I am wrong here.