Monday 24 December 2018

TypeScript, async and Return Type

The other day when writing one TypeScript async method I got into some doubts that made me revisit the last part of this post, the one about the wrapper Promise that the compiler creates for an async method and how this won't be resolved until the internal Promise is resolved. Basically I have one async method that invokes to async methods to return a Person object.


class Person {
    constructor() {
        this.name = "";
        this.city = "";
    }
}
function getFirstId() { //returns a Promise of a string after 1 second
    return new Promise((res, rej) => {
        setTimeout(() => res("1AB2"), 1000);
    });
}
function getPerson(id) { //returns a Promise of a Person after 1 second
    return new Promise((res, rej) => {
        let p = Object.assign(new Person(), {
            name: "Francois",
            city: "Paris"
        });
        setTimeout(() => res(p), 1000);
    });
}

In JavaScript (ES2017), I know I can write the client code in 2 ways:

Doing a return await

async function getFirstPerson() {
    let id = await getFirstId();
    return await getPerson(id); //this return happens after 2 seconds
}

let per = await getFirstPerson(); //all in all we wait 2 seconds

Doing a return

async function getFirstPerson2() {
    let id = await getFirstId();
    return getPerson(id);  //this return happens after 1 second
}

let per = await getFirstPerson2(); //all in all we wait 2 seconds

The first case is pretty clear, return await getPerson(id); returns a Person, that resolves the wrapper Promise that was created and returned when the function was first invoked. The second case is what I explained in that previous post. return getPerson(id); returns a Promise of a Person, and the wrapper Promise won't be resolved until this one is resolved. So for most aspects both codes are equivalent.

The doubt for me when writing equivalent code in Typescript was with the return types. For the second function I was writing:

async function getFirstPerson2(): Promise<Person>{
    let id = await getFirstId();
    return  getPerson(id);  //returns really a sort of Promise>
}

let per = await getFirstPerson2();
    

The TypeScript compiler allows this and compiles it to the JavaScript above. The return is not returning a Person, but a Promise of a Person, with joined to the wrapper Promise created by the runtime gives us a sort of Promise of a Promise of a Person. Anyway, as the external await will wait for the resolution of the inner Promise, the TypeScript compiler is happy with the Promise function signature.

As I explain in the comments to the JavaScript code, depending on whether we do return await or return the return happens 2 or 1 second after the invokation. Anyway, the external await waits for 2 seconds since the method call is launched. There's one more difference related to this that could be important, exception handling. Let's say the Promise returned by getPerson were rejected. In the return await case, a try-catch in getFirstPerson will catch the exception, I mean:

async function getFirstPerson(fail: boolean): Promise<Person>{
    try{
        let id = await getFirstId();
        return await getPerson(id, fail);
    }
    catch{
        console.log("exception caught in getFirstPerson");
        
    }
    return new Person();
}

async function main(){
    console.log(Date.now() + " before calling getFirstPerson");
    //no need for a try-catch here, the one in getFirstPerson catches it all
    let p = await getFirstPerson(true);
    console.log(Date.now() + " person: " + JSON.stringify(p));
}

In the case of return we are just returning the Promise, so we'll need the try-catch for the outer await also, I mean:


async function getFirstPerson2(fail: boolean): Promise<Person>{
    //only catches the getFirstId rejection, but not the getPerson
    try{
        let id = await getFirstId();
        return getPerson(id, fail);
    }
    catch{
        console.log("exception caught in getFirstPerson");
    }
    return new Person();
}

async function main2(){
    console.log(Date.now() + " before calling getFirstPerson");
    //we need a try-catch here for the getPerson rejection
    try{
        let p = await getFirstPerson2(true);
        console.log(Date.now() + " person: " + JSON.stringify(p));
    }
    catch{
        console.log("exception caught in main2");
    }
}

Saturday 22 December 2018

Tour Perret, Amiens

There's a belt of 'department capital cities' surrounding Paris conveniently placed at little more than 1 hour by train (Rouen, Amiens, Reims, Orleans, Troyes) from the magical city, that seem perfect for a day trip. Years ago I did it with Rouen, and lately I had thought many times of going on with exploring some of these cities, but in the end the idea of wandering around Paris always ended up winning over this kind of day trip. Last week I was lucky to spend a few days in Paris again, and finally decided to go for something new and do a day-trip to Amiens the capital of the historical territory of Picardy.

Amiens is mainly known as Jules Verne city. Hey, but Nantes also claims that title, right? Well, indeed he spent his life in Nantes, Paris and Amiens... a smart guy I have to say. Amiens is a lovely city, at least its city center (I did not go any further). Having been in Lille some years ago I already knew that the beautiful architecture of Northern France is very similar to what you find in Belgium, but what quite surprised me is that Amiens has quite of a Brugges feeling. The small canals and the beautiful single-family houses in the St Leu neighbourhood (and the rain, cold and humidity...) brought me many memories of my autumn trip to Brugges years ago. All the city center is really beautiful and is well worth a visit, and the massive gothic cathedral is just gorgeous, but there's an architectural element that I found particularly striking, and that grants the city the right to be in modern Architecture books, the Tour Perret.

The Tour Perret was built in the early 50's and with its little more than 100 meters height it was for some time the tallest building in Western Europe (quite funny to find that in a small city in a country where for good part of the population the irrational hatred for buildings higher than 8 stories makes up one essential part of their identity...), but this kind of past ranking is not particularly interesting to me, what seduced me (mesmerized me almost) is its architecture. The tour is amazingly thin, a square base with 4 windows on each side (becoming 3 in the upper levels). Made of grey reinforced concrete, when seen from the distance one could almost think of it as the belfray of some gothic church, so it's really amazing how nicely it fits in the city scape. A perfect reference point that makes an amazing contribution to the beauty and charm of this small city.

This building is just opposite the main train station, gare du Nord, that was built at the same time also by Auguste Perret in a similar style. It looks pretty massive and interesting (even more with the carefully placed Christmas lights)

Sunday 16 December 2018

FIC Xixón 2018

One of the first posts in this blog, back in December 2009, was about that year's edition of the first posts in this blog, back in December 2009, was about that year's edition of the Xixon Film Festival (FIC Xixon). For the next 3 editions I continued to post my impressions on that year's edition, until 2013, when I was no longer in town during the festival. After a 5 years gap, this November I was in town again during part of the festival, so it was time for me to return. In these five years the festival has gone through some hard times I think. The funding has been reduced (which has forced to cutting its length 1 or 2 days), the director that started in 2012 was questioned for most of his time leading it (I won't add anything to that debate, just say that the only edition under his command that I could experience, 2012, seemed excellent to me) until being replaced for the 2017 edition, and the hardest hit for me (that indeed made me doubt about the survival of the festival) was the closing of the only private cinemas in downtown (that were where most of the films were screened).

Last year I read on the local newspaper an interview to the new director where he was rather positive about the outcome of that edition. The guy seemed pretty modest and sincere, and explained how in spite of all this difficoulties, they had managed to host a pretty decent festival increasing the attendance and the interest of young locals. Currently the festival is held in 3 locations in downtown: Teatro Jovellanos (the beautiful public theatre that has always been the festival's main site), a small, uncomfortable, screening room in "Antiguo Instituto" (this is not new), and a new screening room in the renovated "Escuela de Comercio" (I've never been there, so I can't say how it looks). There's another location in a cultural center quite far from downtown (CMI Pumarin Sur) , that is not new either, and another one in "Teatro de la Laboral", a nice theatre in an amazing, massive complex, but very far from the city center. Finally, 3 rooms in one cinema (Yelmo Cineplex the only commercial cinema in town) located in a mall quite far from the center. With this in mind and being pretty busy with work lately, I was only interested in films screened in "Teatro Jovellanos". I attended to 2 of them.

Saturday 17, The Load, Serbia, Ognjen Glavonic. I pretty enjoyed this fictional work based on a true, little known, dirty event of the Serbia-Kosovo war. A truck driver (before the war he had another job, but now it's the way he's found to put food on the table) has to drive a load from Kosovo to the outskirts of Belgrad. The trip is not particularly exciting but has some odd situations and is good at showing us how in the middle of war people try to go on with their lives, couples get married, teenagers behave as tennagers... As the film develops we (and the driver) will find out that he's carrying the corpses of Kosovar civilians killed during the war, that will get secretly buried in a mass grave in Serbia far from international view. The final part of the movie is poetics and fantastic. Our driver goes through a sort of catharsis talking to his son about how his grandfather had fought against fascism in WWII and decides to document somehow what is happening. The director was present in the cinema and there was a general discussion with him at the end of the film. I could also exchage some impressions with him at the exit. All in all, the guy was an antifascist that had gone through the very difficoult process of doing a work like this in such a nationalistic country like Serbia in order to fight fascism. Absolutely praiseworhty, even when I felt a bit like he was falling too much in the typical European self-demonization. For sure telling this story to make public a hidden and hideous event is important, but we should not forget that Kosovars did as bad, if not worst crap during and after the war, than Serbians. By the way, I absolutely loved the HxC Punk song that closes the film.

Monday 19, One Day, Hungary, Zsofia Szilagyi. Honestly, I did not plan to attend to this film, but one friend of mine wanted to go to 1 session and this one came fit. I have to say that it's been quite a surprise. The plot did not seem to appealing, a day in the life of a Hungarian worker, wife, mother of three and married to an unloyal husband, but it shows masterfully how stressful and painful normal life can be. The film is intense, and at some moments becomes oppresive, immersing us in the little hell in which life has turned for this ordinary woman. One could say that it is disgusting to try to make look the normal life of a European woman with good health as a calvary of pain and suffering, but (have no idea if this was the intent of the director) it works pretty well to remind us of how good we can be at drowning us in misery with our little problems, forgetting how others have to deal with real shit day after day.

Sunday 2 December 2018

Post and No DTO class

Working on an Asp.Net project I've come across a problem that reminded me of an old post. I have one action in one controller that just expects a simple value (a string) as parameter. The action is not for querying data, and though we are not doing a real REST API, at least I wanted to use a POST and not a GET, and pass the value in the post body (not as a querystring).

When passing multiple values the normal thing is just creating a sort of "DTO" object with those values as fields, send it as JSON and let the ModelBinder do its work. But for a single value (or a couple of them) it felt bad to me to create a class with just a single field. This seemed a perfect case for using dynamic. I mean:

//Client side code
  addItem(item: string): Observable {
    return this._remoteService.post(this.url,
      {
        item: item
      });
}


//server side code
        [HttpPost]
        public HttpResponseMessage AddItem(dynamic dto)
        {
            //wrong, myService receives a "null" value
   return Request.CreateResponse(HttpStatusCode.OK, this.myService.AddItem((dto.item as string)));
        }

The thing is that the myService.AddItem was receiving a null value. Checking with the debugger I could see that the dto object with its "item" field was reaching fine the controller. The model binder was using Json.Net and deserializing it to a JObject. JObjec and "dynamic" are designed to work together, so why was I receiving null when passing over the dto.item???

Here is where that old post of mine comes into play. In my code I'm using the as operator to tell the compiler that dto.item is a string, dto.item as string. The problem is that such statement is false, dto.item is a JValue (containing a string we can say), so when the runtime finds that we don't have a string but a JValue (you can read more here), as fails and returns null. So in this case we have to use the cast operator, (string)dto.item, that here does not behave as just a "hint", but performs a explicit conversion from JValue to String. If you are confused, read my old post, where this thing of cast vs as and the 2 different behaviours of the cast operator (hinting vs converting) are well explained.

//server side code
        [HttpPost]
        public HttpResponseMessage AddItem(dynamic dto)
        {
            //works fine
   return Request.CreateResponse(HttpStatusCode.OK, this._virtualDocument.AddFavoriteToCurrentUser((string)dto.item));
        }

Of course I could be using Content-Type: application/x-www-form-urlencoded as explained hereand the ModelBinder should work fine, but there are some differences depending on the ASP.Net version, and I prefered to just follow the json route.