JavaScript Javascript - Wait for array to finish populating javascript wait array of promises,javascript wait array,javascript wait

I am trying to get the value of some array elements. It works for the elements [0], [1], [2], [3], but not [4].

function getBase64() {
  const urls = ['https://i.imgur.com/egNg7JU.jpg',
    'https://i.imgur.com/RLZ7WH1.jpg', 'https://i.imgur.com/qfabBbA.jpg',
    'https://i.imgur.com/Zuh1KaX.jpg', 'https://i.imgur.com/yD7X6Q1.jpg'
  ];

  let base64urls = [];

  const start = async () => {
    await asyncForEach(urls, async (num) => {
      await waitFor(50)
      toDataURL(num, function(dataURL) {
        base64urls.push(dataURL);
      });
    })
    console.log(base64urls);
    console.log(base64urls[4]);
  }
  start()

}

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array)
  }
}

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))

toDataURL simply returns the base64 value of an image. Whenever I try console.log(base64urls[4]), it returns 'undefined'. I do get the correct value for the previous elements. Is there some way to restructure this, or perhaps use a different method of waiting for the array to completely populate before checking for the values of its elements?

EDIT

Here is my toDataURL

function toDataURL(src, callback) {
  const image = new Image();
  image.crossOrigin = 'Anonymous';

  image.onload = function () {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    context.drawImage(this, 0, 0);
    const dataURL = canvas.toDataURL('image/jpeg');
    callback(dataURL);
  };

  image.src = src;
}
Answer:1

It looks like toDataURL is asynchronous and callback-based - either change it so that it returns a Promise and await that Promise, or pass a Promise's resolve into the callback:

async function getBase64() {
  const urls = ['https://i.imgur.com/egNg7JU.jpg', 
                'https://i.imgur.com/RLZ7WH1.jpg', 'https://i.imgur.com/qfabBbA.jpg', 
                'https://i.imgur.com/Zuh1KaX.jpg', 'https://i.imgur.com/yD7X6Q1.jpg'];
  const base64urls = [];
  for (const url of urls) {
    const dataURL = await new Promise(resolve => toDataURL(url, resolve));
    base64urls.push(dataURL);
  }
  console.log(base64urls);
  console.log(base64urls[4]);
}

If you want to change your toDataURL function to return a Promise so you don't have to treat it like a callback:

function toDataURL(src) {
  return new Promise(resolve => {
    const image = new Image();
    image.crossOrigin = 'Anonymous';

    image.onload = function () {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      canvas.height = this.naturalHeight;
      canvas.width = this.naturalWidth;
      context.drawImage(this, 0, 0);
      const dataURL = canvas.toDataURL('image/jpeg');
      resolve(dataURL);
    };
    image.src = src;
  });
}

and then const dataURL = await toDataURL(url)

Answer:2

I'm struggling to figure out how we're supposed to handle submitting a form in React. First time user, failed hard so far. The data in the form is always empty meaning the json is also empty. As far ...

I'm struggling to figure out how we're supposed to handle submitting a form in React. First time user, failed hard so far. The data in the form is always empty meaning the json is also empty. As far ...

  1. react form submission tutorial
  2. react form submission canceled not connected
  3. react form submission example
  4. react form submission
  5. react form submit
  6. react form submit example
  7. react form submit on enter
  8. react form submit get values
  9. react form submit prevent default
  10. react form submit reloads page
  11. react form submit button
  12. react form submit redirect
  13. react form submit refreshes page
  14. react form submit values
  15. react form submit to api
  16. react form submit typescript
  17. react form submit without refresh
  18. react form submit preventdefault not working
  19. react form submit function
  20. react form submit no refresh

I have this bit of code: const data = { x: "Target" } let bar = () => { console.log(this.x) } let final = bar.bind(data); final(); This code returns undefined. Here is the same code, but ...

I have this bit of code: const data = { x: "Target" } let bar = () => { console.log(this.x) } let final = bar.bind(data); final(); This code returns undefined. Here is the same code, but ...

  1. javascript binding arrow functions
  2. javascript arrow binding

I'm building a filter sidebar for my site, I want to be able to open and close the filter lists by pressing a btn. jQuery('.parent > .children').parent().click(function() { jQuery(this)....

I'm building a filter sidebar for my site, I want to be able to open and close the filter lists by pressing a btn. jQuery('.parent > .children').parent().click(function() { jQuery(this)....

  1. side menu open close
  2. side menu open close bootstrap
  3. open close sidebar

Is it possible to create a coverage report with jest for files that satisfy a wildcard path? After the latest release of jest, I can finally create coverage for files specified in the "...

Is it possible to create a coverage report with jest for files that satisfy a wildcard path? After the latest release of jest, I can finally create coverage for files specified in the "...

  1. jest code coverage report
  2. jest code coverage not working
  3. jest code coverage html
  4. jest code coverage threshold
  5. jest code coverage typescript
  6. jest code coverage badge
  7. jest code coverage ignore
  8. jest code coverage sonarqube
  9. jest code coverage branches
  10. jest code coverage unknown
  11. jest code coverage setup
  12. jest code coverage include all files
  13. jest code coverage html report
  14. jest code coverage azure devops
  15. jest code coverage percentage
  16. jest code coverage gitlab
  17. jest code coverage vscode
  18. jest code coverage all files
  19. jest code coverage single file
  20. jest code coverage angular