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

combine elements from a different document using a local field as a key

I'm currently working on a project involving a competition document with a field teams array of objects containing the _id of each team, as well as a score document with a teamId field. The competitions.teams array looks like this: [{_id: 100,..}, {.. ...

purging the setTimeout command

Although I am not very fluent in javascript/jquery, what I am attempting to achieve is to add a timeout to a mouseenter function. This part is not an issue for me, but I also want to clear the timeout if the user exits the element before the timeout comple ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Oops! Looks like the table you're trying to reference hasn't been defined yet

Whenever I attempt to create a table using the Google Visualization API, with PHP & MySQL in the background, I encounter this error message. The database connection is established without issues Generating JSON from the PHP array works correctly The JSON ...

Is there a way to conceal the contents of a page until all the images have finished loading?

I'm currently working on improving the performance of a website that is loading very slowly. I have already reorganized, compressed and minified the JavaScript and CSS files, but the main issue seems to be with the images. The site contains large imag ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Is it possible to send an HTTP request from the renderer process to the main process in Electron?

Currently, I am in the midst of developing an electron video player project. My main objective is to stream video from a readable stream to an HTML video-tag. I am exploring different solutions and strategies to achieve this goal. In particular, I am cur ...

Sending data over a network using Socket and node.js

Trying to update a location on a Google Map using socket.io and node.js. I have 2 different methods for updating the map. There may be some basic issue as I am new to this. 1) Method using an API call that works: app.post('/location', function( ...

Allow frontend JavaScript to retrieve a text file that is restricted to individual users

Trying to articulate my goal is challenging, but I'll do my best to clarify. My objective is to enable JavaScript (or an alternative solution) to retrieve data from a text file on a static site and utilize that data in some way. The challenge here is ...

What is the best way to send data to a view in Laravel using Ajax?

I am facing an issue with my Ajax function that is supposed to call a Laravel view using the data in $paginatedResults returned from another function. However, it keeps returning error 500. I have confirmed that $paginatedResults has the correct data whe ...

Double execution of the Angular customFilter function

My goal is to use a custom filter in Angular to filter an array. Essentially, I have a binding set up like this: {{ myData.winners | getWinnerString }}, which returns an array of items with a length ranging from 1 to 4. If the array consists of more than ...

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 ...

Converting a PHP multidimensional array to JavaScript

I'm facing an issue with printing data from a PHP array in a JavaScript function. The current setup is not producing the desired outcome. Here's how the data is being processed in PHP: $daten = array(); $anzahl = array(); $leads = array(); if ($ ...

Renaming the month in Material-UI React

Using DatePicker from Material Ui, I am trying to change the name of the month. How can this be achieved? For instance, I need to change August to Avqust or March to Mart enter image description here This is my code: <LocalizationProvider ...

Executing a server-side Java function from client-side JavaScript or jQuery on a JSP page

My JSP file has a dropdown list where I can select different entity kinds. Upon selecting an entity kind, I want to populate another dropdown list with the field names associated with that entity kind. This requires calling a JavaScript function when chang ...

Begin the initial function again once the second function has been completed

I have 2 functions in my code: function DisplayAltText(){ var CurrentPhoto = $("#DisplayPhoto img").attr("src"); if( $.browser.msie ) { IECurrentPhoto (CurrentPhoto); } if ($(".PhotoGallery img[src='" +CurrentPhoto+ "&a ...

The $.parseJSON function accurately retrieves valid items but also presents an endless stream of undefined

Currently, I am in the process of developing a Flask application that fetches teams from a football league. The teams_list method returns the result of an AJAX request. While the output is correct, it seems to trigger an infinite loop that significantly sl ...

I am trying to collapse the table header but I am having trouble doing so

@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100); @import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100); body { bac ...

Which files should be included to define the variable $? in jQuery/JavaScript?

I am looking to create a sliding Div over another div in a simple way. The example provided in this Fiddle is exactly what I have in mind, but as someone new to coding, I encountered the warning Uncaught ReferenceError: $ is not defined after transferring ...