Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142353

Async Await Problems with node-canvas loadImage in JavaScript

$
0
0

I can't get an async await function get to work in node js. I use the node canvas repository to load a local image. When trying to access the returned value, it is still a Promise, even if I await it. How can I fix the code?

   async function loadMyLocalImage() {
      const img = await loadImage("pathToMyImage/img.jpg"); // loadImage is a function from node canvas package https://github.com/Automattic/node-canvas#loadimage      
      return img;
    }

    let localImage = loadMyLocalImage();
    console.log(localImage); // returns: Promise { <pending> }

    const canvas = createCanvas(200, 200);
    const ctx = canvas2.getContext("2d");
    ctx.drawImage(localImage, 0, 0); 

This code throws the error:

ctx.drawImage(localImage, 0, 0);
     ^

TypeError: Image or Canvas expected

Because localImage is still a Promise at this point.

How can I wait for my Promise to resolve in this code snippet, before executing the next functions?


Viewing all articles
Browse latest Browse all 142353

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>