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

191
Visualizações
Custom Asynchronous function in JavaScript not working
console.log('Start');
const myFunc = async () => {
 for(let i=0; i<10000000000000; i++){}
 console.log('After for loop');
}
myFunc();
console.log('end');

I want async behaviour using async/await. I want my function to pass the entire function to an event loop same as SetTimeout, SetInterval does so that my main thread can continue to do the rest unless that heavy functionality is running behind the scene.

Expected Output: Start, end, After for loop

Current Output: Start, AFter for loop, end

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

0

Your understanding of asynchronous javascript code is not correct.

Function passed to setTimeout doesn't execute in the background - it executes on the main thread and while that function is executing, nothing else executes.

It's just that the callback function of setTimeout is pushed in to the call stack after the timer has expired and the call stack is empty. This is why other code can execute before the callback function of setTimeout executes.

Some functions provided by the browser such as HTTP requests happen in the background and once they are complete, Javascript will invoke our callback function and once that callback function starts executing, it blocks everything else from executing until that function is popped off the call stack.

Putting your code inside an async function doesn't makes your code asynchronous; it will execute synchronously until the first await expression. (Promises do not make anything asynchronous. They are just a notification mechanism that notifies you of either successful completion or a failure of something that is already asynchronous.)

What you need is another thread that executes the long running code without blocking the main thread. You can do this using a web worker in the browser or worker thread in NodeJS.

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