2017-07-15 61 views
0

我試圖實現同一個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({}) 
+0

是什麼/是不會發生,你是不是/正在期待? – naomik

+0

什麼部分不起作用?我認爲關鍵在於確保只有在確定動畫完成後纔在'cssAnimate()'中調用resolve()。 – gregnr

回答

0

您需要重新分配this.queue一個新的承諾你從 'this.queue.then'

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>

+0

完美,這正是我想要做的,謝謝:) – odakfilo8