In Using promises with apps script I showed how to use promises with HTML service as a better way of managing asynchronous functions (especially from the client.
Promises are a great way to express the order that things have to happen in, and to manage return values from multiple processes. Although Apps Script is synchronous (today anyway), using the same paradigm regardless of whether you are running code on the server or the client makes things more consistent and easy to express.
Apps Script doesn’t support promises at all, but you can use a polyfill to make it so that it does – giving you all the syntactic benefits of promises (even though we can’t really use the orchestration asynchronicity yet).
Here’s how.

Polyfill library

As usual, I have a library that looks after the polyfill for you. Here’s the key.


The code is on Github if you want to make your own.

Using the Polyfill library

Any functions you write will return a promise, instead of an actual result. Any code that wants to consume the result does so like this.
That may seem a little more complicated than
but one immediate benefit you can see is that error and success handling are built in.
Another benefit is that  you can do this
But the biggest benefit is that you can write code that is going to be easily transferable between the server and the client (where you can take advantage of asynchronicity.

Returning promises

Functions need to return a promise rather than a result. Here’s and example of one.
In summary, if the function fails then
if it succeeds

The code

Here’s the key for the library, and it’s also on github, or below. There’s also some test code on GitHub

For more like this, see Google Apps Scripts snippets. Why not join our forum, follow the blog or follow me on Twitter to ensure you get updates when they are available.