1

const promise = new Promise((resolve) => {
    resolve()
})

function move(y) {
    anime({
        targets: '.test',
        translateY: y
    })
}

promise
    .then(() => { move(100) })
    .then(() => { move(-100) })
 
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
<div class="test"> Hello world </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>

I need the .test element to go up by 100 first and only then to go down. This doesn't happen, so I wrote:

promise
    .then(() => { 
        move(100)
        return new Promise((resolve) => {
            setTimeout(resolve, 1000)
        })
    })
    .then(() => { move(-100) })

Is there a better solution? On mdn it is explicitly said:

Callbacks added with then() will never be invoked before the completion of the current run of the JavaScript event loop.

mdn docs about promises

so am I doing something wrong?

1 Answers1

1

following what Andreas said in the comments... I modify the move function to return the promise(anime(params).finished) and there are no curly brackets in the then since I am returning that promise in each step(you can also have .then(()=>{return move(direction)}))

const promise = new Promise((resolve) => {
    resolve()
})

function move(y) {
    return anime({
        targets: '.test',
        translateY: y
    }).finished
}

promise
    .then(() =>  move(100) )
    .then(() =>  move(-100) )
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
<div class="test"> Hello world </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17
  • _"following what Andreas said in the comments..."_ - Bad idea. I missed that the `move()` calls are already wrapped in an anonymous function and that `move()` itself is the problem... It's only the missing `return ...` that "breaks" the script. – Andreas Oct 30 '22 at 12:20
  • @Andreas I looked at what was going on.. to wait on the promise it was actually `anime(params).finished` that was the proper promise to wait on.. not just `anime(params)` – The Bomb Squad Oct 30 '22 at 12:21
  • at any case rate they shouldn't have any more problems so I could call it a day – The Bomb Squad Oct 30 '22 at 12:23