If you use a third-party library that already supports promises, it’s quite easy to use them.
Namely, you need to pay attention to two functions: then () and catch (). For example, we have an API with three methods: getOrder (), updateOrder (), and deleteOrder (), each of which returns a promise:
Each call then () creates the next step in the chain of promises. If an error occurs anywhere in the chain, a catch () block is called, which is located behind the failed portion. The then () and catch () methods can either return a value or a new promise, and the result will be passed to the next then () operator in the chain.
Callbacks to promises
One of the first techniques, which is useful to learn when switching from a callback to promises, is the conversion of callbacks to promises. The need for this can arise if, for example, you are working with a library that still uses callbacks, or with its own code written with their application. It is not so difficult to go from callbacks to promises. Here is an example of converting a function called Node fs.readFile, based on callbacks, to a function that enables promises:
The main thing in this function is the Promise constructor. It takes a function that, in turn, has two parameters – resolve and reject, which are also functions. Inside of this function, all the work is performed, and when we terminate, we call resolve in case of success, and reject if there was an error.
Values to promises
In ES6 there are a couple of convenient helper functions for creating promises from normal values. This is Promise.resolve () and Promise.reject (). For example, you might have a function that needs to return a promise, but which handles some cases synchronously:
Note that you can pass anything (or nothing) when calling Promise.reject (), however, it is recommended that you always pass the Error object to this method.
Simultaneous execution of promises
Promise.all () is a convenient method for concurrently executing an array of promises. For example, say we have a list of files that we want to read from the disk. Using the previously created function readFilePromise, the solution to this problem might look like this: