Embracing Error Handling with ES6 Promises

I am seeking clarification on how errors travel through a series of then continuations to a catch continuation.

Consider the following code:

Promise.reject(new Error("some error"))
       .then(v => v + 5)
       .then(v => v + 15)
       .catch(error => console.log(error));

Upon reaching line 1, we encounter a rejected promise. When the first continuation, .then(v => v + 5), is executed, the original rejected promise remains untouched. The same applies for line 3. As a result, none of the subsequent then continuations are executed. Instead, when the catch continuation is reached, the original object containing the error is passed along as the result.

Can I confirm that this assumption is accurate?

Answer №1

Absolutely, it is evident from the specification:


2.2.7. The method then is required to return a promise.

promise2 = promise1.then(onFulfilled, onRejected);

2.2.7.4. If onRejected is not a function [[or not specified]] and promise1 is rejected, then promise2 must also be rejected with the same reason as promise1.


To clarify, the intermediate then's are not exactly "skipped", nor does the promise simply "pass through" them (although one could possibly perceive it that way); instead, the promises they generate are rejected for the same cause as the initial promise.

Moreover, it would be more precise to refer to these rejections rather than errors (even though an error might often be the basis of a rejection). Additionally, it is customary to term these as "handlers" rather than "continuations".

Answer №2

Is the original rejected promise returned as is?

No, the then method creates a new promise and returns that because it doesn't know the result yet. However, this new promise is immediately rejected with the same reason as the original promise when it rejects. The same process occurs for the promise from line 3, and the final promise in line 4 is then resolved with the result of the catch callback.

In ES6 promises, at least, which you were specifically asking about. Other promise implementations like Creed optimize by simply returning the input promise when they already know it is rejected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

jQuery Autocomplete - Showing array of options upon selecting input field in Internet Explorer

After encountering an issue with the autocomplete feature in a web application, I posted a question on Stack Overflow. The provided answer solved the problem in Chrome, but unfortunately, it did not work in Internet Explorer 8 or 9, and possibly earlier ve ...

What sets apart window.app=new Vue({}) versus const app = new Vue({}) when included in app.js within a Vue.js environment?

What exactly is the difference between using window.app and const app in main.js within Vue? import question from './components/Questions.vue'; Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken; window.App = new Vue({ ...

Tips on utilizing variables instead of static values when calling objects in JavaScript

How can I make something like this work? I tried putting the variable in [], but it didn't work. Can someone please help me out with this? Thank you. const obj = { car : "a" , bus: "b" }; const x = "car" ; ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

Evaluate One Input Value to Determine Another Input Value

Hey there, I've made an update to the fiddle but let me clarify what I'm trying to achieve. My goal is not to implement form validation as I already have that covered with the HTML5 "required" attribute. What I'm aiming for is to customize t ...

What is the reason behind the for of loop breaking within an async function instead of properly awaiting the execution?

Update 2: I made changes to use setTimeOut instead, which fixed the issue. Check out the accepted answer for details on what was causing the error. The code below is now functioning properly. async function getSlices() { const imgBuffs = await sliceImg ...

When trying to find a substring within a string in JavaScript, the "else if" statement may not be triggered

I'm currently working on creating a Hangman game using HTML and JS. Most of the code is functioning properly, but I've hit a roadblock. For some reason, one part of my if else statement isn't working correctly. Here's the line of code: ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

How to trigger an Angular (ionic) view update following an HTTP post request

Is there a way to update the expression in my view after making an HTTP post request? I have tried using the $scope.$apply function, but it gives me an error from ionic.bundle.js saying "$digest already in progress". Could this be a mistake on my part or ...

Choosing a nested object within a JavaScript object

Is there a way to select the style contents of an object within another object? The data consists of a json encoded array. In my scenario, I am using data[i].replies and getting 2. How can I access data[i].userstyles instead? It seems to be an object. I ...

Discovering applied styles based on component props in Material-UI v5 using browser developer tools

When working with Material UI v4, I found it easy to identify which styles are applied by component props classname using browser dev tools. This allowed me to override specific styles of the component effortlessly. However, in Material UI v5, I am unsure ...

Using jQuery JSONP only functions with URLs from the same site

I am looking to send a request to an API that returns data in json format. The API is located on a sub-domain of the domain where my script will be running (although currently it's on a completely different domain for development, localhost). My unde ...

Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below: +------+---------+----+----+----+----+-------+----------+ | Year | Subject | A | B | C | F | Total | PassRate | +------+---------+----+----+----+----+-------+----------+ | 2015 | Maths ...

Testing an asynchronous generator function in Jest using unit tests

I need help writing a unit test for a generator function where I am struggling to properly mock a read stream object (ReadStream). Here is the function I'm trying to test: public async *readChunks(file: string, chunkSize: number): AsyncIterableIter ...

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

Dealing with promise errors in ES6 - How to manage errors effectively

I have a simple code snippet that I've been working on: return Location.findById(locationId) .then(doc => { if(doc) { console.log('Found a matching record.....proceed to delete'); return Location.remove({_id: locationId ...

Error 404 in NodeJS: Page Not Found

I recently started working with NodeJS to develop an ecommerce application. I have a ready-made design and all the front-end components built using AngularJS code. Everything seems to work fine - when clicking on any menu, the page content changes along wi ...