Question:
I am working on a project in which I use fabric.js- I take image address from database.
- Replace a placeholder image on the canvas.
- And then save the canvas as a PNG with ajax.
When I run this code and console log index at different points I saw that the main loop runs through and after that Image replacement part logs index and even later ajax is done.
pseudocode
I am new to javascript, I tried learning about asynchronous methods but they aren’t making sense to me that if they are useful in my case. If you need more information comment below. Thanks
Answer:
You need to re-arrange your code. You already know the answer because you know how the code behave but perhaps you’re not familiar with the techniques. Firstly you need to do this:saveCanvas()
on each iteration of the loop. Therefore you need to execute it only on the completion of the last setSrc()
:If you have better answer, please add a comment about this, thank you!