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…
Rico Suter
SOFTWARE ENGINEERING
EDIT
Aspect-oriented programming JavaScript Promise TypeScript