Introduction to the Promise API

localForage exposes a Promise-based API. The Promise API is another modern web standard. Promise provides a good solution for implementing asynchronous code without ending up with the famous pyramid of doom, also known as callback hell. Take a look at this website to learn more: http://callbackhell.com.

We won't be able to explore how they work in any detail, but here's a quick summary to give you an idea so that the rest of the code doesn't scare you too much.

As its name implies, a promise represents a vow to deliver something at a later point in time, unless something goes wrong, thereby making the promise impossible to respect. There are two basic possible outcomes for a promise:

Promises can be in three different states:

You should also know that there are two functions that we can call on a Promise object:

Earlier, when we've created our MediaService interface, we defined the loadMediaCollection method as loadMediaCollection(name: string): Promise<MediaCollection<T>>. Based on what we've just explained, you should have an idea of what this declaration means. Just in case, here it goes: when this method is called, it will immediately (that is, synchronously) return a Promise<MediaCollection<T>> object. This Promise object will later receive the result or an error.

Since TypeScript has excellent support for promises and also generics, you can see that our promises have a generic type. Check out Basarat's book if you want to learn more: https://basarat.gitbooks.io/typescript/docs/promise.html.

We will stop here with promises, but there's much more to learn! For more information, you can refer to this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise.

In later chapters, we will learn about observables, which are like promises on steroids. If you're curious already, then check out the official website at https://rxjs-dev.firebaseapp.com.