Async/Await does not work with callback

Asked

Viewed 417 times

3

I have a function that converts an image to base 64 but I want only when the console.log('1') run; should appear is the place where I run a post but even inside the arrowFunction it makes the request on the server before it finishes converting the image and that of the error.

async getImageUrl(event, contentIndex: number) {
  await this.toDataUrl(event, (base64image) => {
    console.log(base64image);
    this.base64image = base64image;

  });
  console.log("1");
}

toDataUrl(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    const reader = new FileReader();
    reader.onloadend = () => {
      callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}
  • You have to put async / await in all toDataUrl levels. In function itself, onload and Arrow functions below.

1 answer

3


There are different ways to chain asynchronous functions. In this case toDataUrl() is an asynchronous function that uses callbacks. This cannot be combined with async/await that way. That is, or use the await and toDataUrl() returns a Promise, or else toDataUrl() returns a callback and chains the code inside the callback.

The two variants would be like this:

Using callback:

async getImageUrl(event, contentIndex: number) {
   this.toDataUrl(event, (base64image) => {
    console.log(base64image);
    this.base64image = base64image;
    
    // aqui podes escrever o resto do código
    console.log("1");
  });
}

toDataUrl(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    const reader = new FileReader();
    reader.onloadend = () => {
      callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

Using Promise:

async getImageUrl(event, contentIndex: number) {
  const base64image = await this.toDataUrl(event);
  console.log(base64image);
  this.base64image = base64image;
  // aqui podes escrever o resto do código
  console.log("1");
}

toDataUrl(url, callback) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = () => {
      const reader = new FileReader();
      reader.onloadend = () => {
        resolve(reader.result);
      };
      reader.readAsDataURL(xhr.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  });
}

Find a variant of Promise and callback (without async/await) here too: When to use Success: Function() and . done(Function()) in asynchronous requests?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.