Sunday 29 April 2018

Promises and the Event Loop

I've been reading some documents/articles about the JavaScript event loop (particularly for node.js) and I've found the explanation for what I had noticed in this post regarding awaiting an already resolved promise and the "jumping out" of the async function.

This series looks particulary good. The documentation about the event loop tends to be confusing (particularly the node.js documentation, this discussion helps to clarify it a bit though), but this one seems rather clear (hope it's not simplifying things too much and getting things not fully correctly).

The main idea is that the event loop goes through several phases, traversing several queues where different events/handlers/callbacks have been enqueued. There are 2 "intermediate queues" with a sort of high priority, as they are checked several times per iteration (one time after the traversal of any of the other queues). One of these 2 queues is the Micro task queue. This queue is used for Promises, well, for Promises callbacks, I mean, the handlers attacched to a Promise via then or catch. These callbacks/handlers are added to that queue when the corresponding Promise is resolved. If you add the handlers to an already resolved Promise, the handlers are added to the queue. So contrary to Tasks in .NET, the callback is not executed immediately, but added to the queue. This is what explains the behaviour that I mentioned in my previous article. An example (I'm not using await this time, just then().

let p1 = Promise.resolve("hi");
p1.then(it => console.log("the result is: " + it));

console.log("after resolve and then");

p1.then(it => console.log("and again is: " + it));

// after resolve and then
// the result is: hi
// and again is: hi

You can see how the "console.log" is executed before the "then handler" that got added in a previous line to an already resolved Promise. This answer fully matches with my understanding of Promises and the queue.

When a promise fulfills or rejects, the promise library puts tasks onto the queue for all the attached then or catch handlers. (If a then or catch handler is attached after the promise fulfills or rejects, then the task is put on the queue immediately.)

Thursday 26 April 2018

Reentrant Function

The wikipedia article about coroutines makes an interesting read. In simple terms we can say that a coroutine is a function with multiple entry points, so that it can exit and start its execution later in a different point.

This should sound familiar. You could create a reentrant function by means of a closure, that would keep a state dictating what to do in the ensuing call. Both in C# and JavaScript the yield and await keywords allow us to create reentrant functions (well, await is a bit different, we could say that the function is reentring itself). Indeed, the terminology used in JavaScript, generator, is in accordance with the Computer Science nomenclature used to define a limited type of coroutines.

The thing is that invoking a generator function (javascript) or an iterator method (C#) return a generator/IEnumerable-IEnumerator object on which we will invoke the next or MoveNext methods. So we don't really have a reentrant function, but invocations on the same method of an object that maintains state. If we really want the effect of invoking a reentrant function we can easily leverage a generator/Iterator. I'm using C# iterators for my samples, it would be basically the same in JavaScript.

We can define a Factory method that will return a reentrant function (delegate). This factory method contains a local function defining an iterator and creates a closure that manages the iteration.

        public static Func<string> CreateMessageProvider<T>()
        {
            IEnumerator<string> messageProvider(){
                yield return "Bonjour";
                yield return "Hola";
                yield return "Hello";
                
            }

            IEnumerator<string> enumerator = messageProvider();
            return () => {
                if (!(enumerator.MoveNext())){
                    throw new Exception("Finished");
                }
                return enumerator.Current;   
            };
        }

//main

coroutine = CreateMessageProvider<string>();
Console.WriteLine(coroutine());
Console.WriteLine(coroutine());
Console.WriteLine(coroutine());

We can generalize the above code to create a reentrant function from any provided IEnumerable:

        public static Func<T> CreateCoroutine<T>(IEnumerable<T> enumerable)
        {
            IEnumerator<T> enumerator = enumerable.GetEnumerator();
            return () => {
                if (!(enumerator.MoveNext())){
                    throw new Exception("Finished");
                }
                return enumerator.Current;   
            };
        }

Monday 23 April 2018

Converted Idiot

I have a particular disdain for those that coming from a non-Muslim background (their families are not Muslim and the society where they live is not mostly Muslim) decide on their own accord to convert to Islam. One thing is that you are indoctrinated into it since birth, and another thing is that you decide to freely plunge into it. Choosing to be a slave and lock your chains... Europeans that convert to Islam have a tendency to embrace the worst parts of Islam and adhere to the Salafist/Fundamentalist crap. For me authorities should do a close follow-up of anyone converting to Islam in Europe.

On the other side I hate far-right, racist, xenophobic, ultra-nationalist scum. While I think that some of the political parties that the mainstream media classify as far-right are not really far-right (I don't like the French Front National, but honestly I would not say that they are a bunch of neo-nazis), AfD (Alternative fur Deutschland) falls into the real far-right side for me. Their only good thing, their anti-Islamisation stance, does not make up for all the xenophobic and ethnic nationalist views shown by many of their high level members.

One could think that the only point where AfD militants and Muslims could converge is in a street fight, but to my astonishment I've just found about one pretty vocal AfD member that has converted to Islam!. You can also watch this video.

Maybe someone could think that this is not so odd, as the good relations between Nazi Germany and Islamists are well known. Hitler was a supporter of Hassan al-Banna and the Muslim Brotherhood, and had Haj Amin al-Husseini, the Grand Mufti of Jerusalem, as guest in Berlin for several years. One huge SS division, SS Handschar, was made up mainly by Muslims, and Himmler had a fascination for Islam and for how it created "fearless soldiers". Well, I guess many far-right idiots can be OK with Islam as long as it stays in "lands of Islamic culture" (I mean, areas where it has been dominant for centuries), but when an "European aboriginal", living in Europe converts to Islam, it would sound as an act of treason. For me it's an act of stupidity. I would happily embrace a culture more advanced than that of my ancestors, but embracing a Middle Age ideology... no way.

Well, it seems the guy finds that Christianity has turned too open and liberal (it no longer burns gays in the stake!), while Islam represents the conservative moral values that he likes. Nice... It remains me of when Conservative Christian groups and Muslims joined together in France some years ago to protest against Gay marriage.

Friday 13 April 2018

Rue de la Honte

Life is full of contrasts, pleasure and pain, beauty and horror. Many times we experience them in sequence, just one after another, and it makes us greater appreciate the good ones and greater hate the bad ones. In last december I was enjoying a beautiful winter afternoon stroll around Paris. I was in one of those many areas of Paris "intra-muros" that don't have any particular attraction for the average tourist but that I profoundly love. Areas where traditional Parisian stone buildings mix with high-rise buildings of the 70's, "quartiers populaires" where you still can feel the positive part of the "mix of cultures" and the mixité sociale, where a higher presence of European, Asian and non-muslim African population has prevented the brutal islamisation process of similar neighbourhoods on the other side of the Peripherique. In this occasion I'm talking about Belleville and Menilmontant.

While walking along the Boulevard de Belleville, when reaching the Couronnes Metro station, out of urban curiosity I decided to deviate a bit and take a look at one of the perpendicular streets. I thought it would be similar to Rue Oberkampf, that is just a few blocks away and I know quite well, but not, this street was pretty different. First thing I saw was an Islamic shop full of shit, where you could find all the elements of Muslim communitarism that you could have nightmares about. The most shocking was to find islamic comics to turn kids into "good (salafist) muslims, to teach them to separate and despise "the others", us, the infidels.

I realised this street, rue Jean-Pierre Timbaud had to be a street I had read about some time ago, a street where bobo's and salafists live against. I continued to inspect the street and it was sickening, nauseating, the street is infested with Islamist shops and libraries and ice of the cake, a salafist mosque, la "mosquée Omar", one of the biggest factories of fanatics and terrorists in France.

I took some pictures, but I was so full of hate that my hands were trembling. As strong as that hate was the feeling of impotence, not being able, not daring, to set on fire that salafist mosque and the Islamist shops in that Street of Shame (Rue de la Honte).