Created
June 8, 2016 23:31
-
-
Save domenic/46776bb71a2f885f79013130cd5301aa to your computer and use it in GitHub Desktop.
"last" with cancelation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var pending = { then: function () {} }; | |
// operation must accept as its first argument a cancel token | |
// if your operation does not support cancelation, use a shim: | |
// last((_, ...args) => realOp(...args)); | |
module.exports = operation => { | |
let latestPromise = null; | |
let previousCancel = null; | |
return function () { | |
if (previousCancel) { | |
previousCancel(); | |
} | |
const cancelToken = new CancelToken(c => previousCancel = c); | |
const promiseForResult = operation.call(this, cancelToken, ...arguments); | |
latestPromise = promiseForResult; | |
return promiseForResult.then( | |
value => { | |
if (latestPromise === promiseForResult) { | |
return value; | |
} else { | |
cancel throw; | |
} | |
}, | |
reason => { | |
if (latestPromise === promiseForResult) { | |
throw reason; | |
} else { | |
cancel throw; | |
} | |
} | |
); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment