Is it safe to resolve a promise multiple times?

Solution 1:

As I understand promises at present, this should be 100% fine. The only thing to understand is that once resolved (or rejected), that is it for a defered object - it is done.

If you call then(...) on its promise again, you immediately get the (first) resolved/rejected result.

Additional calls to resolve() will not have any effect.

Below is an executable snippet that covers those use cases:

var p = new Promise((resolve, reject) => {
  resolve(1);
  reject(2);
  resolve(3);
});

p.then(x => console.log('resolved to ' + x))
 .catch(x => console.log('never called ' + x));

p.then(x => console.log('one more ' + x));
p.then(x => console.log('two more ' + x));
p.then(x => console.log('three more ' + x));

Solution 2:

I faced the same thing a while ago, indeed a promise can be only resolved once, another tries will do nothing (no error, no warning, no then invocation).

I decided to work it around like this:

getUsers(users => showThem(users));

getUsers(callback){
    callback(getCachedUsers())
    api.getUsers().then(users => callback(users))
}

just pass your function as a callback and invoke it as many times you wish! Hope that makes sense.