Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful:

function loadImage (url = '', callback = () => {}) {
  utils.loadImage(url, () => {
    callback()
  }, () => {
    loadImage(url, callback)
  })
}

In order to make it return a Promise, the following adjustment was made:

function loadImage (url = '', callback = () => {}) {
  return new Promise((resolve, reject) => {
    utils.loadImage(url, () => {
      // where should we utilize resolve and reject?
      callback()
    }, () => {
      loadImage(url, callback)
    })
  })
}

The challenge now is determining the correct placement for resolve and reject...

Answer №1

function fetchImage(url) {
  return new Promise(resolve => {
    utils.fetchImage(url, resolve, () => {
      fetchImage(url).then(resolve);
    });
  });
}

Note: An improved version suggested by Bergi can be seen below:

function fetchImage(url) {
  return new Promise(resolve => {
    utils.fetchImage(url, resolve, () => resolve(fetchImage(url)));
  });
}

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 pencil-drawn pixel on the canvas is positioned off-center

Currently, I am using p5.js to draw pixels on canvas with a pencil tool. However, I have encountered an issue where the pixel does not appear centered when the size of the pencil is set to 1 or smaller. It seems to be offset towards the left or right. Upo ...

Puppeteer cannot fully render SVG charts

When using this code in Try Puppeteer: const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen'); const linkHandlers = await pa ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Prevent unnecessary clicks with Vue.js

In my vue.js application, there is a feature to remove items. The following code snippet shows the div element: <div class="ride-delete" @click="delete"> <p>Delete</p> </div> This is the function used to handle the click ...

Validation of a string or number that is not performing as expected

I have been working with the yup library for JavaScript data validation, but I am encountering unexpected behavior. Despite thoroughly reviewing their documentation, I cannot pinpoint where I am misusing their API. When I run the unit test below, it fails ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file. While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files. The scenario con ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

Tips for customizing the appearance of a Material-ui Autocomplete element

I am facing an issue with my Autocomplete component that is being used in three different places on the same page, each requiring unique styling. How can I dynamically pass styling information from where the Autocomplete is rendered to its component file? ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...

I am unable to execute Parcel in my project as it is not generating a distribution folder with the compiled file

I'm in need of some assistance in identifying and resolving an error that I'm having trouble understanding. To start, I initialized the project with the command: npm init -y Next, I installed Parcel using: npm install --save-dev parcel I then ...

A sleek CSS text link for a stylish video carousel

I am attempting to create a CSS-only text link to video slider within our Umbraco CMS. Due to the limitations of TinyMCE WYSIWYG, I am restricted in the amount of code I can use as it will strip out most of it. So far, I have developed a basic CSS slider ...

How do you go about installing the most recent version of a module through Private NPM?

When using a private npm registry, I have noticed that some common commands do not seem to be functioning properly: npm install without specifying a specific @version :: issue npm outdated :: issue npm update :: issue npm view <private-packag ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

Submitting a form with AJAX and additional fields can be accomplished by including the extra fields in

Imagine a scenario where I am working with a basic form like the one below <%= form_for(@category) do |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@category.errors.count, "erro ...

There seems to be an issue with the CSV file, possibly indicating an error or the file may not be an SYLYK file when

After developing a node.js script to convert an array object into CSV format using the "objects-to-csv" library from NPM, I encountered an issue when opening the generated CSV file in WPS and Microsoft Office. The warning suggested that there was either an ...