0

This question is the same, but the answers didn't work.

Attempting to await a function inside an async static function generates this error: Uncaught SyntaxError: await is only valid in async function.

Both functions are static. Why doesn't this work?

    static async getImageDataFromFile(file) {
        // Create promise.
        let promise = $.Deferred();

        // Create reader.
        let reader = new FileReader();

        // Process image.
        reader.onload = function(e) {
            // Get data URL for image.
            let dataUrl = reader.result;

            // Get image data.
            let imageData = await this.getImageDataFromDataUrl(dataUrl);

            promise.resolve(imageData);
        }

        // Read image from hard disk.
        reader.readAsDataURL(file);

        // Return promise.
        return promise;
    }


   static getImageDataFromDataUrl(dataUrl) {
      // Create promise.
      let promise = $.Deferred();

      // Create new image object.
      let image = new Image();

      // Read image properties when loaded.
      image.onload = function() {
         // Wrap data in object.
         let data = {
            image: image,
            width: image.naturalWidth,
            height: image.naturalHeight,
         }

         // Resolve promise.
         promise.resolve(data);
      }

      // Start loading image.
      image.src = dataUrl;
   }
Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • 2
    The `reader.onload` function is not `async`, so it can't use `await`. It doesn't matter that it's inside an async function. – Barmar Sep 01 '20 at 06:19
  • @Barmar thanks for the fast and helpful answer! could you post as an answer so you can get credit? thanks. – Crashalot Sep 01 '20 at 06:21
  • You can only use `await` when its nearest containing function is `async`. Use: `return new Promise((resolve) => { const reader = new FileReader(); reader.onload = () => { resolve(this.getImageDataFromDataUrl(reader.result)); }` – CertainPerformance Sep 01 '20 at 06:21
  • @CertainPerformance thanks! Barmar mentioned this, and it's now fixed. Hoping to award the answer to someone. – Crashalot Sep 01 '20 at 06:22
  • You can't really use `async` or `await` when you're dealing something that isn't already a promise API - you need to convert the callback API to promises instead (and only), see the canonical – CertainPerformance Sep 01 '20 at 06:23

0 Answers0