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

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

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 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