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

135
Visualizações
Async/await executing all immediately

Quite new to coding in general and not used async/await much before. I'm trying to get an enemy in a little maze game I'm making to move up, left, down, right, repeat.

Problem I have is that the function just executes everything at once instead of waiting. I know I'm missing something, but can't put my finger on it. Can anyone advise?

async function enemyMovement() {
  enemyCSSVertical = -50;
  enemyCSSHorizontal = 400;
  enemyX = 9;
  enemyY = 10;
  await enemyUp();
  await enemyLeft();
  await enemyDown();
  await enemyRight();
}

// move up
async function enemyUp() {
  setTimeout(() => {
    console.log("up");
    enemyCSSVertical += -50;
    enemy.css("top", enemyCSSVertical);
  }, 1000);
}

//move left
async function enemyLeft() {
  setTimeout(() => {
    console.log("left");
    enemyCSSHorizontal += -50;
    enemy.css("left", enemyCSSHorizontal);
  }, 1000);
}

async function enemyDown() {
  setTimeout(() => {
    console.log("down");
    enemyCSSVertical += 50;
    enemy.css("top", enemyCSSVertical);
  }, 1000);
}

async function enemyRight() {
  setTimeout(() => {
    console.log("right");
    enemyCSSHorizontal += 50;
    enemy.css("left", enemyCSSHorizontal);
  }, 1000);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to create a promise in your move functions and resolve it within the timeout

async function enemyUp() {
  var p = new Promise(function(resolve,reject) {
    setTimeout(() => {
      console.log("up");
      enemyCSSVertical += -50;
      enemy.css("top", enemyCSSVertical);
      resolve("Finished");
    }, 1000);
  }
  return p;
}
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