Providing status responses following the usage of Promises for onload and onerror situations

I am currently experimenting with using JavaScript's onload and onerror functions to determine if a page or image loads successfully. However, I am facing difficulties in accessing the status variable when trying to assign it to read the status. Additionally, I am exploring the use of promises, as suggested in the provided answers, but I still find myself confused.


const validateInput = (input) => {
  const errors = {};
  ... 

    if(!(isImgURlValid(input)))
    {
      errors = `incorrect image URL'` 
    }
    ... 
  return errors;

const isImgURlValid = (path) => {
  let img = document.createElement('img');
  img.src = path;  
  let valid
 const promise = new Promise(resolve => {
    const img = new Image();
    img.onload = () => resolve({path, "status": 'ok'});
    img.onerror = () => resolve({path, "status": 'error'});
     img.src = path;
});
promise.then(function(val) { 
  console.log(val); 
  valid = val.status
}); 
console.log (valid)
}

//using async causes issues with rendering functions
export const renderImgUrlInput = ({ input, label, type, size, required, meta: { touched, error } }) => (
  <div className={
    cs('form-group', size, {
      'has-error': touched && error,
      'required-input' : required
    })
  }>
    <label className="control-label" htmlFor={input.name}>{label}</label>
    <input {...input} placeholder={required ? 'Required' : ''} className="form-control" /> 
    {touched && error &&
      <span className="help-block">{error}</span>
    }
    {touched && !error &&
      <h1 className="help-block">{error} 'Image worked'</h1>
    }
  </div>
)

Answer №1

const checkImgURL = (url) => {
    return new Promise((resolve, reject) => {
        const image = document.createElement("img");
        image.src = url;
        image.onload = resolve;
        image.onerror = reject;
        image.src = url;
        document.body.appendChild(image);
    });
};

checkImgURL("https://www.example.com/image.jpg")
    .then(() => console.log("Image URL is valid"))
    .catch(() => console.error("Invalid image URL"))

Answer №2

It is important to remember to return the created promise from isImgURlValid back to the caller. By doing this, the caller can then wait for the promise to resolve and use the result to determine if the provided image source is valid.

For a practical example inspired by the question code, you can input an image source into the text box and press Enter to trigger the event.

const isImgURlValid = (path) => { 
  return new Promise(resolve => {    
    const img = new Image()
    img.src = path;
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    
    // img starts loading src when added to the DOM
    document.body.append(img);
    document.body.removeChild(img);
  });
};

const validateInput = async (input) => {
  const errors = {};
  if (!await isImgURlValid(input)) {
    errors.url = "invalid";
  }
  return errors;
};

document.getElementById("input").addEventListener("change", ({target}) => {
  validateInput(target.value).then(console.log);
});
<input id="input" type="text" />

Answer №3

If you're new to promises, it seems like you've already gone through the suggested duplicate, but here's a fresh take on how you can rewrite your code:

const isImgUrlValid = (path) => {
  return new Promise( (resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({path, "status": 'ok'});
    img.onerror = () => reject({path, "status": 'error'});
     img.src = path;
  });
};

// Handle success or failure with then and catch
isImgUrlValid('https://www.gravatar.com/avatar/153828e74e3fb5f7aeb19a28a78a378a?s=32&d=identicon&r=PG&f=1').then( status => console.log('image found') );
isImgUrlValid('invalid_uri').then( _ => console.log('I will never be called') ).catch( err => console.log('no image found') );

By using resolve for success and reject for failure, you can follow the typical promise flow.

Consumers of the promise can chain then or catch to handle success or failures accordingly.

If you want to use this code within a function and check asynchronously, you can do so by making the caller an async function:

const validateInput = async () => {
  let isValidImage = false;
  try {
   isValidImage = await isImgUrlValid( path );
  } catch (ex) {
    // Handle incorrect image
    
  }
};

Keep in mind that validateInput now implicitly returns a promise, so you'll need to treat it as such.

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

Bold does not show up after clicking

Within my project, I developed an internal email system. Whenever a new message comes in, the subject column in my table is displayed in bold to indicate that the message has not been read yet. Here is the code snippet: <?php while($row = mysqli_ ...

Error: Failed to set the 'src' property of null when attempting to change the image source

When I click on an image, I want to change its source. Here is the HTML code: <div class="character"> <input id="1200" name="vocation_select" type="radio" value="1200" style="display: none" ></input> <label id="label_profesji" for="12 ...

Leverage the power of an Express server to manage a Node.js application

I have a node.js application that communicates with a REST API hosted on a separate server. To control this application, I want to create a web interface using express.js which includes HTML, CSS, and Javascript. How can I enable the browser to interact w ...

When leaving the page, onBeforeUnload function aborts any ongoing HTTP requests

When attempting to send an http request using the fetch API upon leaving the page, I am encountering a blockage of the request. Is there a solution to this issue without resorting to using an async function or waiting for the request to complete, which tri ...

Discovering duplicate values in a JSON object using JavaScript (JQuery)

Below is a JSON object that contains information about various materials: [ { "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000", "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)", "uns": "S45000", "temperatura": "NL", "p ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

Having trouble pinpointing the source files that are loading .js in the <head> section of my Magento website

My console is showing me three 404 errors related to missing .js files in the head section of my website. Even though I don't actually need these files, I want to stop receiving the 404 errors as they are affecting my analytics and SEO. The files caus ...

Change UL to a JSON format

I am attempting to transform an entire unordered list (UL) and its child elements into a JSON object. Here is the approach we took: function extractData(element) { element.find('li').each(function () { data.push({ "name": $(this).fi ...

What could be causing my overloaded controller methods to not be receiving requests correctly?

Within my view, I have a page called PrintPatientConsent.aspx that I need to call for two different types. However, only the default action method is being called by default, even when passing parameters. Here is the code snippet for reference: [Accept ...

Issue encountered when converting Jquery val() split() function to Vanilla JavaScript

As I work on transitioning my code from Jquery to Vanilla JS, there is a particular code snippet that is proving difficult to convert: function updateTextBox(nehemyah) { var delfino = $("#campotxt").val().split("\n"); delfino.remove(nehemyah); $ ...

Running JavaScript code without blocking the main thread

While studying JavaScript and JSON, I encountered some issues. I have a script that functions with JSON data, but the performance of my code is not optimal. The code only works when I debug it step by step using tools like Firebug which leads me to conclud ...

Having trouble transferring file object from reactjs to nodejs

Hey there! I am relatively new to nodejs and React, and currently, I'm working on a project that involves sending a selected file from the front end (React) to the back end (Node). The goal is to upload the file and convert it into a JSON object. Howe ...

When a directive generates an element, the ng-click function may not function as expected

I am developing a custom directive using angularJS. The directive is supposed to replace my custom element with pagination elements. However, the generated elements by the directive contain an ng-click attribute whose value is a function from the controlle ...

How to utilize Vue.js 3, Axios, and Express to showcase data retrieved from an array or

Trying to display a single post fetched from an express API using Vue has been challenging. The issue lies in the fact that the values declared in the template for post.title & post.body are not being displayed as expected when accessing post.value. ...

Load a page and sprinkle some contents with a slide effect

I am brand new to jQuery and just starting out, so please excuse me if this question seems basic or silly. I would like the header and footer of my page to stay in place while the center content slides in from the right side when the page loads. This websi ...

Tips for executing a function only once within the animation loop in Three.js

Is there a way to call a function only once when a certain condition is met in Three.js? I am currently sampling the frames per second (FPS) to send it to an external service. The FPS is sampled and averaged over time, and the average value is sent after 1 ...

Getting data from an API using a Bearer Token with React Hooks

I am currently developing a React application that is responsible for fetching data from an API. This API requires Bearer Token Authorization. To handle this, I have implemented useState() hooks for both the token and the requested object. Additionally, th ...

Customizing Background Colors with ChartJs and React

In my React project, I am looking to implement a Line chart styled as an Area Chart using the 'react-chartjs-2' library. Here is the desired outcome I aim to achieve, with a background fill below the line: https://i.sstatic.net/zOgzz.png Below ...

Is there a way to link the id selector with the item's id?

In my app, I have a list of items with buttons that can be liked. To ensure uniqueness, I am utilizing the id selector. My goal is to use the item's id and connect it to the id selector for proper distinction. How can I retrieve the id of each item a ...

Which task runner should I use for my NodeJS application - Gulp or Grunt?

Imagine I have Stylus with nib, Jade, Passport, Mongoose, along with other modules that I integrate into my NodeJS application. Given that all pre-compilers are functioning well as Node modules, is it necessary to use gulp or Grunt to streamline the proce ...