Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!