I think the confusion is arising from the fact that, based on your use of res
, and rej
here, you are likely calling this from within a promise constructor, along the lines of
function setStore(newID, value) {
return new Promise(function(res, rej) {
this.dataStore.set(newID, value).then( (foo) => {
try{
this.var = foo;
res({val: foo});
}catch(e){
rej(e);
}
}, (e) => {
rej(e);
});
});
}
By the way, the (e) => { rej(e); }
part at the end could be rewritten as e => rej(e)
, which in turn could be rewritten as rej
.
But anyway, you don't need any of that surrounding machinery to create and return your own promise, because this.dataStore.set
and/or the ensuing call to then
already creates a promise, which you can return as is. Instead of creating your own new promise, and then resolving your new promise with the little hash based on the result passed to then
, just return the hash--that will become the value of the resulting promise. Instead of rejecting your new promise when the call to dataStore.set
fails, just let the failed promise be itself.
So you shouldn't need to do anything more complicated than
function setStore(newID, value) {
return this.dataStore.set(newID, value).then(foo => {
this.var = foo;
return {val: foo};
});
}
An error occurring in the this.var = foo; return {val: foo};
part (but how could it?) will automatically throw the promise into failure state. A failure resulting from this.dataStore.set
will yield a failed promise as is, and there is no need to catch it and rethrow it--the failure will progress merrily down the chain.
Use this as:
setStore('abc', 123)
.then(hash => console.log(hash.val))
.catch(e => console.log("The sky is falling", e));
As a matter of clarification, in the following:
promise.then(success, failure)
an error arising in the success
callback is not handled in the failure
callback. A failure in the success
callback would be handled in successive stages of the chain. You could handle a failure in success
(or promise
itself) with
promise.then(success).catch(failure)