Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda