【问题标题】:Asynchronous Method Chaining异步方法链
【发布时间】:2017-07-15 12:52:50
【问题描述】:

我正在尝试实现相同asynchronous 方法的链接。基本上我想做的就是打电话给animation.animate({}).animate({})。完成第一个动画方法后,需要调用第二个动画方法。

这就是我所做的,我认为它已经接近了,但我仍然找不到如何让它工作。

class Animation {

    constructor() {
        this.queue = new Promise((resolve,reject)=> {resolve()})
    }  

    animate(params) {
        this.queue.then(() => {
            return this.cssAnimate(params);
        })
        return this;
    }

    cssAnimate(params) {
        return new Promise((resolve,reject) => {
        //do stuff to animate

        params.el.addEventListener('transitionend', () => {resolve()})
        })
    }

}

let animation = new Animation();

animation
    .animate({}) 
    .animate({})

【问题讨论】:

  • 发生了什么/没有发生你没有/期望的事情?
  • 哪个部分不工作?我认为关键是确保只有在您确定动画完成时才在cssAnimate() 中调用resolve()

标签: javascript asynchronous ecmascript-6 promise


【解决方案1】:

您需要使用从 'this.queue.then' 获得的新 Promise 重新分配 this.queue

class Animation {

  constructor() {
    this.queue = Promise.resolve()
  }  

  animate(params) {
    this.queue = this.queue.then(() => this.cssAnimate(params))
    return this;
  }

  cssAnimate(params) {
    const {el, clz} = params
    
    return new Promise(resolve => {
      el.addEventListener('transitionend', resolve)
      el.classList.toggle(clz)
    })
  }
}


document.querySelector('#play').addEventListener('click', () => {
  let animation = new Animation();
  const el = document.querySelector('.box')

  animation
    .animate({
      el,
      clz: 'left'
    }) 
    .animate({
      el,
      clz: 'left'
    })
})
.box {
  background-color: pink;
  width: 100px;
  height: 100px;
  margin-left: 0;  
  transition: all 3s linear;
}

.left {
  
  margin-left: 200px;
}
<div class="box"></div>
<button id="play">Play</div>

【讨论】:

  • 完美,这正是我想做的,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2016-12-26
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
相关资源
最近更新 更多