I'm interested in exploring the idea of using an approach similar to .NET's cancelation tokens in JS for async task cancelation. Since the cancelation "flag" is effectively an eventual value, it seems like promises are well-suited to modeling the token. Using a promise for a cancelation token would have the added benefit that the eventual result of any arbitrary async operation could be used as a cancelation token.
First, has this idea been fully explored somewhere already? We've discussed this idea on es-discuss in the past, but I don't remember any in-depth analysis. Second, it occurs to me that the current promise API isn't quite ideal for cancelation tokens, since we don't have synchronous inspection capabilities. For example, suppose that we have this async function: async function f(cancel) { let canceled = false; cancel.then(_=> canceled = true); await cheapOperation(cancel); if (canceled) throw new CanceledOperationError(); await expensiveOperation(cancel); } Now, when the `canceled` flag is checked before `expensiveOperation`, it may be the case that the `cancel` promise has already been resolved (i.e. [[PromiseState]] is "fulfilled"), but the `then` callback has not executed yet. In such a case `expensiveOperation` would be started, even though a cancelation has been requested. For this reason, it seems like some kind of synchronous inspection ability is required in order to use promises as cancelation tokens. With synchronous inspection, the above function would be written something like: async function f(cancel) { await cheapOperation(cancel); if (cancel.isFulfilled()) throw new CanceledOperationError(); await expensiveOperation(cancel); } Without synchronous inspection, I think we'd need to introduce some new API for cancelation tokens. Thoughts? (For the purposes of this discussion, let's avoid discussing the relative merits of cancelable promises vs. cancelation tokens.)
_______________________________________________ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss