title: WinJS, return a promise from a function which may or may not be async
body: <p>I have a situation where my WinJS app wants to call a function which may or may not be async (e.g. in one situation I need to load some data from a file (async) but at other times I can load from a cache syncronously).</p>
  
  <p>Having a look through the docs I though I could wrap the conditional logic in a promise like:</p>
  
  <pre><code>A)
  return new WinJS.Promise(function() {  // mystuff });
  </code></pre>
  
  <p>or possibly use 'as' like this:</p>
  
  <pre><code>B)
  return WinJS.Promise.as(function() { // mystuff });
  </code></pre>
  
  <p>The problem is that when I call this function, which I'm doing from the ready() function of my first page like this:</p>
  
  <pre><code>WinJS.UI.Pages.define("/pages/home/home.html", {
  
      ready: function () {
  
           Data.Survey.init().done(function (result) {
  
              // do some stuff with 'result'
  
          });
      }
   });
  </code></pre>
  
  <p>When it is written like 'A' it never hits my done() call.</p>
  
  <p>Or if I call it when it's written like 'B', it executes the code inside my done() instantly, before the promise is resolved. It also looks from the value of result, that it has just been set to the content of my init() function, rather than being wrapped up in a promise.</p>
  
  <p>It feels like I'm doing something quite basically wrong here, but I'm unsure where to start looking.</p>
  
  <p>If it's any help, this is a slimmed down version of my init() function:</p>
  
  <pre><code>    function init() {
  
      return new WinJS.Promise(function() {
  
          if (app.context.isFirstRun) {
  
              app.surveyController.initialiseSurveysAsync().then(function (result) {
                  return new WinJS.Binding.List(result.surveys);
              });
          } else {
  
              var data = app.surveyController.getSurveys();
              return new WinJS.Binding.List(data);
          }
      });
  }  
  </code></pre>
  
  <p>Does anyone have any thoughts on this one? I don't believe the 'may or may not be async' is the issue here, I believe the promise setup isn't doing what I'd expect. Can anyone see anything obviously wrong here? Any feedback greatly appreciated.</p>