Did you know ... | Search Documentation: |
JavaScript Promise that can be aborted |
A Promise
resolves or is rejected. As Prolog waits for a
specific promise on a call to await/2
we may want to abort long running operations. This may be achieved using
the class
Prolog.Promise
which extends Promise
. To make
the promise abortable the executor function must have an
abort
property. Below is the code for
Prolog.promise_sleep()
that implements this schema.
First we create the executor and use properties on the function
itself to represent the necessary state information (here, the running
timer). Next, we add an abort
property the clears the timer
and runs the reject
callback of the Promise
.
Finally we return an instance of Prolog.Promise
which
implements .abort()
.
promise_sleep(time) { const f = function(resolve, reject) { f.reject = reject; f.timer = setTimeout(() => { f.timer = undefined; resolve(true); }, time*1000); }; f.abort = function() { if ( f.timer ) { clearTimeout(f.timer); f.timer = undefined; f.reject("abort"); } } return new Prolog.Promise(f); }