JavaScript decorator to add pre- and post-logic to a Promise

March 6, 2016, Software Development

In this blog post, I’ll describe the simple concepts of JavaScript Promise decorators. They are a simple way to add logic which is run before and after the exection of a Promise (a.k.a. aspect-oriented programming). As soon as you see my two samples, you’ll get the idea…

The first sample shows a Promise decorator function which shows and hides a loading screen (I use TypeScript typings to show the types of function arguments):

function showLoadingScreen<T>(action: () => Promise<T>) {
    ShowLoadingScreen();
    return action().finally(function () {
       HideLoadingScreen(); 
    });
}

The decorator can be used in the following way:

function longRunningAction() {
    return showLoadingScreen(function () {
        console.write("Start");
        return delay(10000).then(function () {
            console.write("Stop");
        });
    });
}

The second sample shows how to mimic the using keyword from C# in JavaScript:

function using<T>(service: IDisposable, action: () => Promise<T>) {
    return action().finally(function () {
        service.dispose(); 
    });    
}

The using function can be used as follows:

var myService = new MyService();
using(myService, function() {
    return myService.getItem(1).then(function (item: any) {
        console.write(item);
    });
});

As you can see, Promise decorators are very easy to implement and easy to understand. But nonetheless, they can improve your code readability a lot… What do you think? Comment below…

Tweet about this on TwitterShare on FacebookEmail this to someoneShare on TumblrShare on LinkedIn

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax