我有一系列承諾鏈,需要足夠的時間才能完成。下面是示例鏈設置:NodeJS - 如果收到事件,則終止承諾鏈
myJob1()
.then(myJob2)
.then(myJob3)
.then(myJob4)
.then(myJob5)
.then(myJob6)
.catch(myJobError);
在當該作業正在運行,如果在UI的人認爲取消它的平均時間,怎麼能在任何階段/函數執行它被取消?
什麼是可能的解決方案?
我有一系列承諾鏈,需要足夠的時間才能完成。下面是示例鏈設置:NodeJS - 如果收到事件,則終止承諾鏈
myJob1()
.then(myJob2)
.then(myJob3)
.then(myJob4)
.then(myJob5)
.then(myJob6)
.catch(myJobError);
在當該作業正在運行,如果在UI的人認爲取消它的平均時間,怎麼能在任何階段/函數執行它被取消?
什麼是可能的解決方案?
沒有辦法取消承諾(記住每一個都返回一個新的承諾)或清除then
回調。
可能您正在尋找類似redux-observable
的東西,您可以在其中指定子句,直到承諾執行實際爲止。
查看更多詳細:https://github.com/redux-observable/redux-observable/blob/master/docs/recipes/Cancellation.md
作爲替代我只能建議你創建和管理的一些標誌確定是否需要或沒有進一步的處理:
// Inside each of promises in chain
if (notCancelled) {
callAjax(params).then(resolve);
}
或拒絕:
// Inside each of promises in chain
if (cancelled) {
// Will stop execution of promise chain
return reject(new Error('Cancelled by user'));
}
修改多個作業功能代碼的一種替代方法可能是檢查作業之間的用戶取消標誌。如果這種檢查的粒度是不是太當然,那麼你可以異步設置(有些)全球取消標誌,並沿該線繼續:
let userCancelled = false;
let checkCancel = function(data) {
if(userCancelled)
throw new Error("cancelled by user"); // invoke catch handling
return data; // pass through the data
}
myJob1()
.then(myJob2).then(checkCancel)
.then(myJob3).then(checkCancel)
.then(myJob4).then(checkCancel)
.then(myJob5).then(checkCancel)
.then(myJob6).then(checkCancel)
.catch(myJobError);
不要忘記,如果你做檢查被取消在工作內部標誌,你所需要做的就是拋出一個錯誤,讓它在承諾鏈上向下冒泡。
真的需要更多的信息,例如。特別是當你說客戶。你的客戶是否有某種形式的RPC?取消承諾鏈將很容易,但它將命令傳遞到後端,這是棘手的部分。 – Keith
[如何取消EMCAScript6(香草JavaScript)承諾鏈](https://stackoverflow.com/questions/29478751/how-to-cancel-an-emcascript6-vanilla-javascript-promise-chain) – TheCog
不能取消,但你可以做一個拒絕。然後停止其餘的被調用。你必須在每個工作中測試一些東西,如果測試通過了,你會返回一個新的被拒絕的承諾,例如'return Promise.reject('reason')' –