M
M
montakarlo2020-05-09 17:36:18
JavaScript
montakarlo, 2020-05-09 17:36:18

Help with JS async?

I'm making a mini-game, there is a character's health, by pressing "Q" 10 is taken away from him using the damage function. We need to return something to the fight function so that at the moment when the health is below 0, the message "finish"
is displayed in the console . The fight function should finish its execution when the health is 0

let health = 50

async function fight(){
  addKeysEvents();
  return new Promise((resolve) =>

  })
}

function damage(){
  health = health -10;
}

function addKeysEvents(){
  document.addEventListener('keydown', function(event){
    if (event.code == 'KeyQ'){
      damage();
    }
  })
}
fight()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dubolom Unicellular, 2020-05-09
@duboloms

if (health <= 0){
  console.log("финиш бл*");
}

Changed:
And also:
function damage(){
  health -= 10;
}
function addKeysEvents(){
  document.addEventListener('keydown', function(event){
    if (event.key == 'Q'){
      damage();
    }
  })
}

B
be_a_man, 2020-05-09
@be_a_man

Promise calls resolve on success and reject on failure.
In your case, most likely so, but the architecture of the code is very strange

async function fight(){
  addKeysEvents();
  return new Promise((resolve) =>
    health <= 0 && resolve('finish')
  })
}

fight().then( v => { console.log(v) })

V
Vladimir, 2020-05-10
@Casufi

montakarlo , Let's try to think.
You have a piece of code in the fight function

async function fight(){
  addKeysEvents();
  return new Promise((resolve) =>

  })
}

And for some reason this async function, although it returns a Promise, is not logical, the functions are made asynchronous so that you can do await in it and work with promises as with regular functions
https://developer.mozilla.org/uk/docs/Web/JavaScri.. Then ,
you have a call to addKeysEvents(); is higher than return new Promise although it is logical to stuff it inside, then addKeysEvents can return a promise that will resolve when life is less than zero
https://habr.com/ru/company/mailru/blog/269465/
if you still leave fight with async, you can remove the return new Promise((resolve) => construction
and use await and leave the promise only in addKeysEvents

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question