In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this:

let promise         = new Promise((resolve, reject) => {
    imgToDisplay.onload = () => {
        resolve(imgToDisplay.width);
    }
})
.then((result) => {
    window.URL.revokeObjectURL(imgToDisplay.src);
    if (result >= 20)
        reject('Image width too large');
})
.then(() => {   
    //Some action is taken with the image file here if it was not rejected
})
.catch((e) => {
    alert(e.message); //An error occurred: "reject is not defined"
});

In the second then(), I forgot to either call reject or resolve. What mistake did I make in this part of the code?

Answer №1

When outside the Promise constructor, you are unable to directly call reject as it is out of scope. However, throwing an error within the .then block can guide the flow of control to the subsequent .catch, essentially bypassing intermediary .thens:

let promise         = new Promise((resolve, reject) => {
  imgToDisplay.onload = () => {
    resolve(imgToDisplay.width);
  }
})
.then((result) => {
  window.URL.revokeObjectURL(imgToDisplay.src);
  if (result >= 20)
    // This will trigger a rejection of the Promise:
    throw new Error('Image width too large');
})
.then(() => {   
  // Do something with the image file here unless it was rejected
})
.catch((e) => {
  alert(e.message); //This occurred, although "reject is not defined"
});

In this scenario, if the condition causing the rejection of the Promise can be evaluated within the Promise constructor, then it's possible to invoke reject within the constructor itself:

let promise         = new Promise((resolve, reject) => {
  imgToDisplay.onload = () => {
    if (imgToDisplay.width >= 20) {
      reject('Image width too large');
    }
    resolve(imgToDisplay.width);
  }
})

Answer №2

It is recommended to use throw instead of using reject in the then callback

let promise         = new Promise((resolve, reject) => {
    imgToDisplay.onload = () => {
        resolve(imgToDisplay.width);
    }
})
.then((result) => {
    window.URL.revokeObjectURL(imgToDisplay.src);
    if (result >= 20)
        throw 'Image width too large';
})
.then(() => {   
    //Do something with the image file here if it is not rejected
})
.catch((e) => {
    alert(e.message); //An error occurred, but "reject is not defined"
});

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

Tips for seamlessly integrating XHP and ReactJS for a component's implementation

Imagine this scenario: a blog with a posts feed. Upon loading the page, three <PostCard>s are already loaded from the server-side. As the user scrolls down or clicks a Load more button, new post cards should be dynamically added to the page. We have ...

Obtain the selected dropdown value and transfer it to the controller seamlessly without the need to reload the page

Currently, I am facing an issue with two dropdown lists in a bootstrap modal - CATEGORY and SUBCATEGORY. The values in the SUBCATEGORY list depend on the selection made in the CATEGORY list. My goal is to retrieve the selected value ID and pass it to my co ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

Using AJAX autocomplete with Sys.Serialization.JavaScriptSerializer

I implemented an ajax autocomplete feature in ASP.NET where a method from a web service is called to fetch postal codes. public string[] GetNames(string prefixText, int count, String contextKey) { prefixText = prefixText.Trim(); XmlNodeList list; ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Discovering if an input field is read-only or not can be achieved by using Selenium WebDriver along with Java

Currently, I am utilizing selenium webdriver along with Java to create a script. One issue we are encountering is that certain fields become disabled after clicking on a button. We need to determine if these fields are transitioning into readonly mode or ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

Ways to modify the pre-defined value in a TextField

I encountered a situation where I have a form with pre-filled data from a specific country. The data is initially read-only, but the user can click on the edit button if they wish to make changes. The issue arises when trying to edit the value in the Text ...

In Vue.js, I only want to retrieve and display the parent's ID or name once for each of its child components

<td v-if="currentId != loop.id" class="text-center"> <div :set="currentId = loop.id">{{ loop.id }}</div> </td> <td v-else></td> Looking to achieve a specific layout like this This invo ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

Is this filter selector in jQuery correct?

It appears to function correctly, but I am unsure if there is room for improvement. I aim to target any HTML element with a class of edit-text-NUM or edit-html-NUM and adjust its color. This is the code snippet I am currently utilizing... jQuery(document ...

AngularJS Input field fails to update due to a setTimeout function within the controller

I am currently working on a project that involves AngularJS. I need to show a live clock in a read-only input field, which is two-way bound with data-ng-model. To create this running clock effect, I am using a JavaScript scheduler with setTimeout to trigge ...