Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
I need help in making the JS event loop wait for a functions execution

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

    for loop
    {
        console.log("start");

        // To go through the image addresses array retrieved from database

        for loop
        {
            console.log("Inside Second loop");

            // To Go through placeholder images or layer of images 
            // There can be multiple images on canvas to replace
            
            // replace Image happens here

            console.log("BeforeImageChange");
            imgToChange.setSrc(imgAddressFromDB){
                console.log("AfterImageChange");
            }
        }
        
        function saveCanvas(){
            //function to save canvas as a Image done through ajax to php
            console.log("AfterSaving");
        }

        saveCanvas();
        console.log("End");
    }

console.log output is like

    "start"
    "Inside Second loop"
    "BeforeImageChange"
    "End"
    "AfterImageChange"
    "AfterSaving"

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try calling saveCanvas() inside the setSrc method, this way saveCanvas will be called after calling AfterSaving console.

about 4 years ago · Juan Pablo Isaza Report

0

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:

for loop
{
    console.log("start");

    // To go through the image address retrieved from database

    for loop
    {
        console.log("Inside Second loop");

        // To Go through placeholder images or layer of images
        // replace Image happens here

        console.log("BeforeImageChange");
        imgToChange.setSrc(imgAddressFromDB){
            console.log("AfterImageChange");

            // You already know that code inside here
            // gets executed last
    
            function saveCanvas(){
                //function to save canvas as a Image done through ajax to php
                console.log("AfterSaving");
            }

            saveCanvas();
            console.log("End");
        }
    }
}

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():

for loop
{
    console.log("start");

    // To go through the image address retrieved from database

    let setSrcCount = figureOutHowManyTimesTheForLoopBelowLoops();

    for loop
    {
        console.log("Inside Second loop");

        console.log("BeforeImageChange");
        imgToChange.setSrc(imgAddressFromDB){
            console.log("AfterImageChange");

            setSrcCount --;

            if (setSrcCount === 0) {
                function saveCanvas(){
                    //function to save canvas as a Image done through ajax to php
                    console.log("AfterSaving");
                }

                saveCanvas();
                console.log("End");
            }
        }
    }
}

The code can be made more readable if you use Promises:

function setSrc(imgAddress) {
    return new Promise((ok,err) => {
        imgToChange.setSrc(imgAddress,function () {
            ok();
        });
    });
}

async function functionContainingLoops() {

  for loop
  {
    console.log("start");

    // To go through the image address retrieved from database

    for loop
    {
        console.log("Inside Second loop");

        // To Go through placeholder images or layer of images
        // replace Image happens here

        console.log("BeforeImageChange");

        await setSrc(imgAddressFromDB);

        console.log("AfterImageChange");
    }

    function saveCanvas(){
        //function to save canvas as a Image done through ajax to php
        console.log("AfterSaving");
    }

    saveCanvas();
    console.log("End");
  }
}

ContainingLoops()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!