search
HomeWeb Front-endCSS TutorialA Peek at New Methods Coming to Promises

A Peek at New Methods Coming to Promises

JavaScript's Promise is one of its most praised features. The direct built-in native asynchronous components in the language has opened a new era, which not only changed our encoding methods, but also laid the foundation for other powerful APIs (such as fetch!).

Let's review the features that Promise got when it was first released and what new features will be obtained next.

Don't understand the concept of Promise? I highly recommend Jake Archibald's article as a primer.

Existing features

Let's take a quick look at what you can currently do with Promise. After JavaScript introduced Promise, it provides an API to perform asynchronous operations and react to their success or failures, a way to create associations around certain data or results that we still don't know about the value of these data or results.

Here are the Promise features we currently have.

Handle Promise

Whenever an asynchronous method returns a promise (for example when using fetch), we can use then() to perform an action when the promise was fulfilled (completed) and use catch() to respond to the promise rejected (rejected).

 fetch('//resource.to/some/data')
  .then(result => console.log('We got it', result.json()))
  .catch(error => console.error('Error occurred', error))

A classic use case is to call data from the API and load the data when it returns, or to display an error message if the data is not found.

Furthermore, in its initial version, we obtained two methods of handling Promise groups.

Parsing and rejecting Promise collections

When the Promise is successfully parsed, it can be fulfilled ; when it is parsed with an error, it can be rejected ; when it is not parsed, it is in a pending state. When the Promise is parsed, it is considered completed regardless of the result.

Therefore, we have two ways to help with the behavior of the Promise group, depending on the combination of states we obtain.

Promise.all is one of the methods. It will only be fulfilled when all the promises are successfully parsed and return an array containing the results of each promise. If one of the Promise fails, Promise.all will enter catch and return the error reason.

 Promise.all([
    fetch('//resource.to/some/data'),
    fetch('//resource.to/more/data')
  ])
  .then(results => console.log('We get an array of results', results))
  .catch(error => console.error('One of the Promise failed', error))

In this case, once one of the members of the collection throws an error, Promise.all will short-circuit and enter catch , or complete when all Promises are fulfilled .

Check out Domenic Denicola’s short article on Promise status to learn more about its wording and concepts.

We also have Promise.race , which immediately resolves to the first Promise it gets, whether it is fulfilled or rejected. After the first promise is parsed, the remaining promises will be ignored.

 Promise.race([
    fetch('//resource.to/some/data'),
    fetch('//resource.to/other/data')
  ])
  .then(result => console.log('first Promise resolved', result))
  .catch(reason => console.error('One of the Promise failed because', reason))

New Features

OK, we're going to turn our attention to the new Promise features we can expect.

Promise.allSettled

The next proposal to add to the Promise family is Promise.allSettled , which, as the name suggests, will continue to execute only if all collection members in the array are no longer in the pending state, whether they are rejected or fulfilled .

 Promise.allSettled([
    fetch('//resource.to/some/data'),
    fetch('//resource.to/more/data'),
    fetch('//resource.to/even/more/data')
  ])
  .then(results => {
    const fulfilled = results.filter(r => r.status === 'fulfilled')
    const rejected = results.filter(r => r.status === 'rejected')
  })

Note that this is different from Promise.all , because we will never enter the catch statement. This is great if we are waiting for a dataset that will enter a different part of the web application, but want to provide more specific emails for each result or perform different actions.

Promise.any

The next new approach is Promise.any , which allows us to react to any fulfilled Promise in the collection, but will only short-circuit if all Promises fail.

 Promise.any([
    fetch('//resource.to/some/data'),
    fetch('//resource.to/more/data'),
    fetch('//resource.to/even/more/data')
  ])
  .then(result => console.log('a batch of data has arrived', result))
  .catch(() => console.error('all Promises failed'))

This is a bit like Promise.race except Promise.race is short-circuited on the first parsing. Therefore, if the first Promise in the collection is parsed with an error, Promise.race will continue to execute. Promise.any will continue to wait for the rest of the items in the array to parse before continuing to execute.

Demo

Some of them are easier to understand using visualization, so I created a small playground that demonstrates the difference between new and existing methods. (The demo part is omitted here because the original text does not provide specific code or link)

Summarize

While they are still in the proposal stage, community scripts can simulate the new approaches presented in this article. For example, any and reflect of Bluebird are good polyfills we wait for the browser to support improvements.

They also show how the community has used this asynchronous pattern, but building them into the language opens up new possibilities for data fetching and asynchronous parsing in web applications.

In addition to then and catch , you can also pass finally to Promise, which Sarah Drasner wrote in a detailed article about which you can check out. (The link is omitted here)

If you want to know about the upcoming Promise Combinator, the V8 blog just released a short explanation with links to official specifications and proposals. (The link is omitted here)

The above is the detailed content of A Peek at New Methods Coming to Promises. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Iterating a React Design with Styled ComponentsIterating a React Design with Styled ComponentsApr 21, 2025 am 11:29 AM

In a perfect world, our projects would have unlimited resources and time. Our teams would begin coding with well thought out and highly refined UX designs.

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Apr 21, 2025 am 11:26 AM

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons

SVG Properties in CSS GuideSVG Properties in CSS GuideApr 21, 2025 am 11:21 AM

SVG has its own set of elements, attributes and properties to the extent that inline SVG code can get long and complex. By leveraging CSS and some of the forthcoming features of the SVG 2 specification, we can reduce that code for cleaner markup.

A Few Functional Uses for Intersection Observer to Know When an Element is in ViewA Few Functional Uses for Intersection Observer to Know When an Element is in ViewApr 21, 2025 am 11:19 AM

You might not know this, but JavaScript has stealthily accumulated quite a number of observers in recent times, and Intersection Observer is a part of that

Revisting prefers-reduced-motionRevisting prefers-reduced-motionApr 21, 2025 am 11:18 AM

We may not need to throw out all CSS animations. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

How to Get a Progressive Web App into the Google Play StoreHow to Get a Progressive Web App into the Google Play StoreApr 21, 2025 am 11:10 AM

PWA (Progressive Web Apps) have been with us for some time now. Yet, each time I try explaining it to clients, the same question pops up: "Will my users be

The Simplest Ways to Handle HTML IncludesThe Simplest Ways to Handle HTML IncludesApr 21, 2025 am 11:09 AM

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that

Change Color of SVG on HoverChange Color of SVG on HoverApr 21, 2025 am 11:04 AM

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover,

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software