Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I clone a Promise?

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?

like image 690
apscience Avatar asked May 06 '16 02:05

apscience


1 Answers

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.

like image 163
Bergi Avatar answered Sep 22 '22 06:09

Bergi