• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: I need help in making the JS event loop wait for a functions execution

Resolved: I need help in making the JS event loop wait for a functions execution

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

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
console.log output is like
How can I make it so AfterImageChange happens right after BeforeImageChange and Saving happens before loop end?
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:
But I presume you don’t want to saveCanvas() on each iteration of the loop. Therefore you need to execute it only on the completion of the last setSrc():
The code can be made more readable if you use Promises:

If you have better answer, please add a comment about this, thank you!

javascript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How do I stop the command from happening if the requirements for it to work aren’t sert Discord.js

02/04/2023

Resolved: How to scroll bottom of div at launch?

02/04/2023

Resolved: how to get and read an xml file in a zip file using xml.etree

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.