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:
- The promise can be kept and the something can be delivered.
- The promise cannot be held and an error is returned.
Promises can be in three different states:
- Pending: Not resolved yet
- Fulfilled: Resolved
- Rejected: Failed
You should also know that there are two functions that we can call on a Promise object:
- then(result ⇒ { ... }): The then function can be used to define a success callback function. That callback function will be invoked if/when the promise is resolved successfully. In this example, the result argument of the lambda will be the outcome of the promise.
- catch(error ⇒ { ... }): The catch function can be used to define a failure callback function. That callback function will be invoked if/when the promise is broken. In this example, the error argument of the lambda will be the error raised if the promise is broken.
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.