Note that there are some explanatory texts on larger screens.

plurals
  1. POChain promises and break out on error WinJS
    primarykey
    data
    text
    <p>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?</p> <p>Consider the following pseudo-code example</p> <pre><code> 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); }); </code></pre> <p>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 <a href="http://msdn.microsoft.com/en-gb/library/windows/apps/br229660.aspx" rel="nofollow">any</a> method here some how? </p> <p>thanks</p> <p>*<em>*</em>*EDIT . In case others want to know what my solution looked like based on the accepted answer below it is as follows:</p> <pre><code> 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); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload