Consecutive execution of promises
Sometimes the simultaneous execution of several promises can lead to trouble. For example, if you try to get a lot of resources from the API using Promise.all, it’s the API, and after a while, you will exceed the limit on the frequency of access to it. One solution to this problem is to run the promises sequentially, one by one. Here the Array.reduce method can help us:
In this case, we want to wait until the current call to api.deleteOrder () is completed before the next call. This code demonstrates a convenient way to register an operation that would otherwise have to be rewritten using then () for each item ID:
Another convenient auxiliary function that is available in ES6 is Promise.race. Like Promise.all, it accepts an array of promises and executes them simultaneously; however, the return from it is carried out as soon as any of the promises are executed or rejected. The results of other promises are discarded.
For example, we create a promise that ends with an error after some time, setting a restriction on the operation of reading a file represented by another promise:
A common way to intercept errors in promises is to add a .catch () block to the end of the chain, which will intercept errors that occur in any of the preceding blocks .then ():
The catch () block is called here if either getItem or updateItem fails with an error. But what if we do not need joint error processing and need to handle the errors that occur in getItem separately? To do this, just insert another block catch () immediately after the block with the call getItem – it can even return another promise:
Now, if getItem () fails, we intervene and create a new element.
The code within the then () expression should be treated as if it were inside a try block. And calling return Promise.reject (), and calling throw new Error () will execute the next catch () block.
This means that runtime errors also trigger catch () blocks, so when it comes to error handling, do not make assumptions about their source. For example, in the following code snippet, we can expect the catch () block to be called only to handle the errors that came with getItem, but, as the example shows, it also responds to run-time errors that occur inside the then () expression: