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

158
Visualizações
How to create asynchronous tasks in JavaScript

How to do asynchronous tasks like this:

I want to have two tasks: One would print "foo" after 1 second, and the other one would print "bar" after 2 seconds. I want them to start at the same time, and run asynchronously.

Here's an example of this in python:

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

How do I do something like this in JavaScript? Do I use promises? I don't know how they work. I'm "new" to javascript

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

0

You can use then method of js promises.

function timeout(time_ms) {
  return new Promise(resolve => setTimeout(resolve, time_ms));
}


function main() {
  timeout(1000).then(() => console.log("hello"))
  timeout(2000).then(() => console.log("world"))

  var d = new Date();
  var n = d.toLocaleTimeString();
  console.log(`started at ${n}`)

}

main()

about 4 years ago · Juan Pablo Isaza Relatório

0

I strongly recommend you not to use async but Promise if you want to be good at JavaScript.

Promise is an expression that has a strong algebraic structure, and async-await, on the other hand, they are statements that has complicated rules.

about 4 years ago · Juan Pablo Isaza Relatório

0

Hi!

You can do it like this:

async function hello() {
  setTimeout(() => {}, 1000)
  console.log("hello")
}

async function world() {
  setTimeout(() => {}, 2000)
  console.log("world")
}

async function main() {
  await hello()
  await world()
}

main()

Let me know if that works for you!

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