Sometimes I want to defer the execution of the promise constructor and still be able to define promise chains. I found and slightly adapted the following approach, but since I have little experience with promises I'd like to know
- whether there is a more succinct way to do this?
- what I am losing with this approach?
class Deferred {
constructor() {
this.promise = new Promise((r, e) => {
// arrows use this of their surrounding scope
this.resolve = r;
this.reject = e;
});
this.then = this.promise.then.bind(this.promise);
this.catch = this.promise.catch.bind(this.promise);
this.finally = this.promise.finally.bind(this.promise);
}
}
const sqrAsync = n => {
const d = new Deferred;
d.runPromise = () => typeof n === "number"
? setTimeout(d.resolve, 0, n * n)
: setTimeout(d.reject, 0, new Error("number expected"));
return d;
};
const deferred = sqrAsync(5),
deferred2 = sqrAsync("foo");
deferred
.then(console.log)
.catch(console.error)
.finally(() => console.log("clean up 1st"));
deferred2
.then(console.log)
.catch(console.error)
.finally(() => console.log("clean up 2nd"));
deferred.runPromise();
deferred2.runPromise();
I know that I can achieve this and other desirable properties using userland's Task
/Furture
implementations and I usually do that. However, sometimes I need the ES6 Promise
interop.
To anticipate the why: I want to separate "effectful" computations from the rest of my program.