I have an asynchronous function that returns a promise. The operation should only be performed once. I want all callers of that function to get back the same Promise, but I don't want .catch()
es of one caller to affect another caller. Can I clone a promise, or implement this in another way?
but I don't want
.catch()
es of one caller to affect another caller.
They never1 do (unless you've chained the callbacks, which you don't).
I want all callers of that function to get back the same Promise
Just do it. Promises are immutable values2.
Can I clone a promise?
If you really need3 a distinct object that will follow the original promise (fulfill when it fulfills or reject when it rejects), you can use the then
method without arguments:
var clone = promise.then();
console.assert(clone !== promise);
1: Assuming you use a proper promise library. I think I can remember a case of a library (old jQuery?) where then
callback results changed the state of the promise.
2: In their resolving behaviour, at least. Every promise is still just an object of course.
3: You don't. You really should not. I'm just answering the title question, but you should stop doing weird stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With