0

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);
}
  • 2
    There is nothing waiting for any of these `setTimeout`s to be finished and `async` doesn’t magically change the semantics of `setTimeout`. See [How to make a promise from setTimeout](/q/22707475/4642212). – Sebastian Simon Feb 14 '22 at 17:15
  • 2
    Does this answer your question? [async/await function does not wait for setTimeout to finish](https://stackoverflow.com/questions/49813405/async-await-function-does-not-wait-for-settimeout-to-finish) – Ivar Feb 14 '22 at 17:16

1 Answers1

2

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;
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80