Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
JavaScript: what type of functions can we create to be executed asynchronously?

I’m trying to understand how async functions work in JavaScript and how to write them, but it seems to me that the way the language handles async functions is pretty limited, but I can be wrong and, probably, I did not understand it.

I use Visual Studio Code (v. 1.66.2) and Chrome (v 100.0.4896.88) on Windows 10 X64.

Just for experimental purposes, I wrote a simple heavyLoad() function that gets a delay parameter (that represents a millisecond value) and return true after time elapsed:

function heavyLoad(delay) {        
    let startTime = (new Date()).getTime();
    while(new Date().getTime() < startTime + delay);
    return true;
}

If I write:

heavyLoad(5000);
console.log(“Hello”);

the console.log() function is, obviously, executed after 5 secs, since I have to wait that heavyLoad() function ends.

I’m trying to make heavyLoad() function as asynchronous so that I can read, in the browser console, Hello immediately without waiting for heavyLoad() function but I’m not able to do that: I’ve tried to create a promise object; I tried to use async keyword but nothing works, since I have always to wait that heavyLoad() function ends before reading Hello.

Is it possible to make heavyLoad() function, essentially as it is, an async one as I meant?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use WebWorker and Promise

Write your heavy load script in a separate file.

worker.js

onmessage = function(e) { 
    let startTime = (new Date()).getTime();
    while(new Date().getTime() < startTime + e.data);
    postMessage(true);
}

Run that webWorker in the main script file.

main.js

function heavyLoad(delay) {        
    return new Promise((resolve, reject) => {
        var myWorker = new Worker('worker.js');
        myWorker.postMessage(delay);
        myWorker.addEventListener('message', function(e) {
            // Log the workers message.
            resolve(e.data);
        }, { once: true });
    })
}

console.log("Starting")
console.time()
heavyLoad(5000).then(data=>{
    console.timeEnd()
})
console.log("end")

(Here I'm using console.time method to keep track of the execution time)

about 4 years ago · Juan Pablo Isaza Relatório

0

For timeout there is setTimeout() method in javascript.

So you can simply use:

setTimeout(() => {
  console.log("Hello");
}, 5000);
about 4 years ago · Juan Pablo Isaza Relatório

0

Try following code to understand asynchronous working

function heavyLoad(delay) {        
        return new Promise((resolve, reject)=>{
         
            setTimeout(()=>{
                resolve(true)
            },delay)
        })
    }

    heavyLoad(5000).then(value=>{
        console.log(value)
    });
    console.log("Hello");

It will print hello first as you run the code and true after 5 seconds.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda