javascriptangularjslocalforage

Is there a way to add finally to an existing promise?


I am using localforage which returns a promise for functions such as key() and length(). I am also using $http() which returns a promise for too but it includes a finally() function, which the other does not.

My services down the chain do not know whether localforage or $http makes the request so they all require the same promise structure (finally and then). Is there a way to add finally to the promises that do not already have it?

I have attempted to append $q.defer().promise.finally to my promises from localforage which did not work.

var promise = localforage.length();
promise.finally = $q.defer().promise.finally;
return promise;

Is there another way to achieve this?


Solution

  • If you want to "convert" one promise into another you can use their resolve method to resolve an inner promise (or to adopt the value of the promise). For $q you can use the resolve method here. So basically:

    return $q.resolve(localforage.length());
    

    There's also Promise.prototype.finally coming up soon, so you can scratch $q and use native Promise with a shim. All you got to do is literally use Promise instead of $q (literally).