Sunday, February 11, 2018

Promise.all() for async/await performance improvement

There are long time we have to depend on callbacks for working with asynchronous code. Now, with the most recent Async/Await syntax, writing code in javascript is about to get even better!


Assuming we are creating an music application and want to collect part of a song's details about author and genre. Let's write a function so async returns a value and promise will resolve the rest.

const get_song = async name => {
    const song_   = await search_song(name),
          author_ = await search_author(song_.author),
          genre_  = await search_genre(song_.genre);

    return {
        song_,
        author_,
        genre_
    };
};

get_song("Nếu không là tình yêu");

Very clean and tidy code, but how much time does it take for this job?

search_song: 1 time
search_author: 1 time
search_genre: 1 time
>>> Total: 3 times

We have already known that search_author and search_genre are independent, they can to be collected simultaniously.

Add Promise.all() for awaiting two promises in parallel:

const get_song = async name => {
    const song_ = await search_song(name);

    return Promise.all([
        search_author(song_.author),
        search_genre(song_.genre)
    ])

    .then(response => ({
        song_,
        author_: response[0],
        genre_: response[1]
    }));
};

Although, we messed it up a bit but the both author and title are collected at the same time.

search_song: 1 time
(search_author/search_genre): 1 time
>>> Total: 2 times

The best practice for this job will be:

const get_song = async name => {
    const song_ = await search_song(name);

    const [author_, genre_] = await Promise.all([
        search_author(song_.author),
        search_genre(song_.genre)
    ]);

    return {
        song_,
        author_,
        genre_
    };
};

In this article, we are trying to balance the readability of the code and still maintain the performance improvement from using Promise.all().

Post a Comment

Whatsapp Button works on Mobile Device only

Start typing and press Enter to search