In WinJS, what is the correct way to chain promises if you needed to "break out" of the chain? For instance, if you had .then() functions and a final .done(). What is the correct way to return an error from a then that has others after it?
Consider the following pseudo-code example
function doSomething(){
return new WinJS.Promise(function(comp,err,prog){
filePicker.pickSingleFileAsync().then(function(file){
if(file){ // have a valid file
return readTextAsync(File);
}else{ //else user clicked cancel
return err('No file');
}
}).then(function(text){
if(text){
return comp(text);
}else{
return err('No text');
}
}).done(null, function(error){ //final done to catch errors
return err(error);
});
});// end return promise
} //end doSomething();
doSomething().done(function(text){
console.log(text);
}, function(err){
console.log(err);
});
Now in this simplified example, if a user cancels the filePicker, they should hit the first err("No File"); however this still proceeds to call the next .then(text) which would also return an error('no text') as text is undefined. The overall doSomething().done() error handler returns "No File" here which is what I would expect, but debugging shows the code still calls the "err('No Text')" part of the promise. Is it possible to actually exit the promise chain at this point? Should I look at using the any method here some how?
thanks
***EDIT . In case others want to know what my solution looked like based on the accepted answer below it is as follows:
filePicker.pickSingleFileAsync().then(function (file) {
if (file) {
return Windows.Storage.FileIO.readTextAsync(file);
}
return WinJS.Promise.wrapError("No File");
}).then(function (text) {
if (text) {
return complete(text);
}
return error("no text");
}).done(null, function (err) {
return error(err);
});
undefined
) gets propagated along the success chain, right? – Monniemono