2017-08-16 70 views
0

我有這樣的代碼:觸發連鎖承諾

this.array = []; 
initArrayClicked() { 
    this.clearArr() 
    .then(this.addOneToArray.bind(this)) 
    .then(this.addTwoToArray.bind(this)); 
} 

我有按鈕,當我點擊它調用此函數,並在此赤岸承諾this.array價值到底是[1, 2]和那沒關係。

當我點擊按鈕兩次,this.array每次都有不同的值([1, 2, 1, 2],[2, 1, 2])時,問題就開始了。

我希望當我點擊按鈕時,我的最終結果將是[1, 2]並不重要,我點擊按鈕的方式並不重要。我想問題是,承諾的鏈條沒有變化,我從乞討開始,導致了不希望的結果。

我試圖尋找一個解決方案,但我找不到。

在此先感謝和抱歉我的英語!

+1

你可以發佈你的其他功能嗎? addOneToArray,addTwoToArray –

+1

這不是問題,但請注意,你假設你的承諾永遠不會被拒絕。並進一步考慮JayLane的觀點:請使用Stack Snippets('[<>]'工具欄按鈕)以**可運行的** [mcve]方式更新您的問題。 –

+0

如果你有四次快速點擊,你想得到兩個結果('[1,2]',然後'[1,2]')或**一個**結果(只有一個'[1,2] )? –

回答

1

您可以設置click處理程序null直到Promise鏈完成,然後重新裝click處理程序元素

let handleClick =() => { 
    button.onclick = null; 
    this.array = []; 
    this.clearArr() 
    .then(this.addOneToArray.bind(this)) 
    .then(this.addTwoToArray.bind(this)) 
    .then(() => button.onclick = handleClick.bind(this /* set `this` here */)) 
} 

button.onclick = handleClick.bind(this /* set `this` here */); 
+0

我在這裏給出了一個很不好的例子,一個按鈕觸發此功能。我真正的項目,我有很多按鈕,觸發這個功能,所以這不會幫助我。 – Sagie

+0

您可以在'

0

你說你需要4個輸入快速,重複點擊,只會導致一對。要做到這一點,塊重複調用initArrayClicked

this.array = []; 
this.arrayBusy = false; 
initArrayClicked() { 
    if (!this.arrayBusy) { 
     this.arrayBusy = true; 
     this.clearArr() 
     .then(this.addOneToArray.bind(this)) 
     .then(this.addTwoToArray.bind(this)) 
     .catch(error => { /*...handle errors, don't throw new ones...*/ }) 
     .then(() => { this.arrayBusy = false; }) 
    } 
} 

注意內嵌錯誤處理。最終then被觸發,該catch一定不能拋出錯誤或返回拒絕的承諾。我假設你想這樣做,因爲你沒有將該承諾鏈返回給函數,所以沒有任何其他將能夠處理來自它的錯誤。如果情況並非如此,結構會有所不同。

+0

有沒有辦法可以強制停止目前的鏈接承諾並重新開始? – Sagie

+0

@Sagie _「我沒有辦法強制停止當前的鏈接承諾並重新開始?」_這不是原始問題。請參閱https:// stackoverflow。com/help/how-to-ask – guest271314

+1

@Sagie:Promise沒有「取消」或「中止」語義。如果你用一個[mcve] - 一個**代表性的**例子來更新你的問題 - 我可能會建議一個替代方案來做你想做的事。但不是現在這個問題的基礎。 –