title: Can't get $q promise in Angular factory to work correctly
body: <p>The factory doesn't return anything, it just writes to a json file. I can't figure out how to use $q in this case to be sure it's done writing. </p>
  
  <p>This is causing me problems in a controller, because even if I use a callback, the code does not execute in the correct order..</p>
  
  <pre><code>angular.module('jsonWrite', [])
  .factory('JsonWrite', function($q) {
    var nw = require('nw.gui');
    var fs = require('fs');
    var path = require('path');
  
    var file = "myjsonfile.json";
    var filePath = path.join(nw.App.dataPath, file);
  
    var write = {};
  
    write.writeJson = function(x){
      var deferred = $q.defer();
      fs.access(filePath, fs.F_OK, function(err) {
          if (!err) {
              fs.readFile(filePath, 'utf8', function(err, data) {
              var myObj = JSON.parse(data);
                  myObj = x;
                  fs.writeFileSync(filePath, JSON.stringify(myObj));
              });
          }
  
          else {
              fs.open(filePath, "w", function(err, data) {
                  var myObj = {};
                  myObj = x;
                  fs.writeFileSync(filePath, JSON.stringify(myObj));
               });
          };        
          $q.resolve();
      });
    return deferred.promise;      
    };
  
  return(write);
  
  });
  </code></pre>
  
  <p>This is an example of the controller function, even if there's a callback, JsonWrite is not done writing before StateChanger.changeState executes. This causes heaps of trouble. If I put a $timeout on StateChanger, everything works fine - it executes after JsonWrite is done writing.</p>
  
  <pre><code>$scope.change = function(x){
  
      function write(callback){
          JsonWrite.writeJson(x);
          callback();    
       };
  
  
      function change(){
          writemystuff(function(){
              StateChanger.changeState(); // &lt;- $timeout here and it works
          })
      };
  
  change();
  
  };
  </code></pre>
  
  <p>If anyone can give me an idea on what can be done, I'd be very grateful</p>