Wednesday, March 27, 2019

From Promise to async/await in Typescript Part II

In part I we went through a simple example, simple enough to illustrate what async/await look like and how to use them. This time we can discuss why we want to embrace async/await, instead of our old friend Promise.



The reason is mostly readability. Take a look at these 2 code snippets doing exactly the same thing. The online example can be found here

Bitching your mom with Promise

export function promiseFat(): Promise<string[]> {
const whats: string[] = [];
return fat().then(what => {
whats.push(what);
return damnFat();
}).then(what => {
whats.push(what);
return fuckingFat();
}).then(what => {
whats.push(what);
return whats;
});
}

function fat(): Promise<string> {
return Promise.resolve('fat that sometimes she cause traffic jam');
}

function damnFat(): Promise<string> {
return Promise.resolve('fat that when she goes to snorkeling the sea-level rises and floods little pacific islands');
}

function fuckingFat(): Promise<string> {
return Promise.resolve('fat that light bends when traveling by her side');
}

Bitching your mom with async/await

export async function asyncFat(): Promise<string[]> {
const whats: string[] = [];
whats.push(await fat());
whats.push(await damnFat());
whats.push(await fuckingFat());
return whats;
}

async function fat(): Promise<string> {
return 'fat that sometimes she cause traffic jam';
}

async function damnFat(): Promise<string> {
return 'fat that when she goes to snorkeling the sea-level rises and floods little pacific islands';
}

async function fuckingFat(): Promise<string> {
return 'fat that light bends when traveling by her side';
}

Even if you are a previous Promise lover, like me, I bet you can see the simplicity async/await bring in, not to mention how easily an aged synchronous programmer could understand this syntax at first glance.

According to my experience last few years, most sync programmers get quickly confused and crashed their logic when they see the first code structure with Promise. When you introduce asynchronous to them with such an alien syntax they all just like "WTF, this can't be the reality~!".

I guess async/await really make life easier for them. Quote from the document of async function:

But the syntax and structure of your code using async functions is much more like using standard synchronous functions.


No comments:

Post a Comment