'JavaScript: I'm trying to draw both text and image on a canvas in a loop, and then download it, but only the text shows in the canvas after download

I noticed that the image starts drawing to the canvas (onload image takes time) after the text has been drawn to the canvas (in a loop), how do I go about it, I want the text and image to be drawn, before running another.

(How I want it to be.)

(But how I get it.)

 Object.values(results).map(async listArray => {
      //clear to draw new data to the canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(image, 0, 0, image.width, image.height)
      var im = []

      listArray.map(async data => {
        if (validBase64Image(data?.text)) {
          im = new Image()
          im.onload = () => ctx.drawImage(im, data?.x, data?.y, 100, 100)
          im.src = data.text
        }
        if (!validBase64Image(data?.text)) {
          ctx.fillText(data?.text, data?.x, data?.y)
        }
      })
      downLoadWithCsvTitle(canRef, listArray?.[0]?.text)// download canvas
    })
  }
     ```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source