I have a function loadItems() that loads something async, and then fails or succeeds. Both fail and success callbacks must do something in the library, and then pass it on to the implementer, which can choose to implement fail, or success, or both, or none.
The problem I now have is if the library implements both the success and fail handler, it will always return a new promise that resolves to success.
This is what I have:
// The library:
function loadItems() {
return store.get('todo').then(function(rsp) {
// Save these locally
items = rsp.value || [];
}, function(rsp) {
// Do nothing, but let the user know
alert(rsp.error);
});
}
store.get('todo') (from yet another library) returns a promise. loadItems() has no control over it.
// The library implementer:
function init() {
loadItems().then(showItems);
}
What I want, and expected to happen:
loadItems()runs the async code from the library (store.get())- It implements
successandfailbecause they have mandatory actions - It passes the success/failure on to the implementer
- The implementer only implements
success, because it doesn't care about errors, because the library handled it - So it uses
.then(onSuccess)to 'add another success callback'
What happens instead (with an error):
- The library's failure callback is executed
- A new promise is passed on to the implementer
- The new promise always resolves with success
- The implementer's success callback is fired, with broken result, because the library's success callback didn't fire
Are Promises seriously too cool to have multiple, sync success handlers??
I can imagine even the source library (that defines store.get()) wants to handle the error (for logging sneakily), and then pass success/failure on.
My 'solutions':
- Have
loadItems()' failure callback throw an error. Unfortunately, that meansinit()has to catch it (or the browser whines about it). Not cool. - Use a simple callback to talk back to
init(), instead of a promise, which only fires after a success. That's not good, becauseinit()might choose to handle the error some day.
I'm sure I'm doing something wrong, but I don't see it.
loadItems().init()only cares about the result IF it worked. If not, doesn't matter, but don't executethen()as if it did work. - Deux