String.prototype.replace() only to find you had to have a global flag with a regex? Well not anymore, because now with
String.prototype.replaceAll(), it’s very straightforward and much more readable.
Let’s go see its MDN entry:
String.prototype.replaceAll()method returns a new string with all matches of a
patternreplaced by a
patterncan be a string or a
RegExp, and the
replacementcan be a string or a function to be called for each match.
2. Numeric separators
3. Logical OR assignment operators
Also if you like this feature, check out the logical and operator (MDN here).
This is an interesting feature for sure, so what’s a good use case for this? Borrowing from the MDN we get a good idea here…
“This method is useful for returning the first promise that fulfills. It short-circuits/stops after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike
Promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills. “
What’s a good example of using Promise.any()?
In the weekly SPS UI-guild we actually discussed this new feature (BTW always looking for new members, message Chris N about it!). One cool idea that fellow UI-guild member Ken Korth thought of was …
“…you were trying to get an accurate time from a time server and you were trying many time servers, when the first one came back, you could use any because the rest would be canceled…”
Or Imagine we are hitting an API endpoint and what comes back is relatively large/slow like a large MSTR sales report whose data changes infrequently. We could have a cached API and the live data API BOTH go out and whichever API comes back first is displayed to the user. Cool right?
What’s the difference between Promise.race() and this?
There is a very important KEY difference between the two, basically, Promise.any() vs Promise.race come down to how they handle failing Promises.
- Promise.any() – Brings back the first promise, and only one result. Shows failure when all promises fail.
- Promise.race() – Brings back the first promise that succeeds or fails.
Hopefully, you can start to use these features in your daily workflow, and before you know it we’ll have es2022 features. Happy coding!