0

I am trying to run chrome.runtime.sendMessage to get the information from the server. I am using this information to determine which page to display in my chrome extension. The problem is chrome.runtime.sendMessage is an async function and it is not jiving well with app.config. Is there a way I can turn chrome.runtime.sendMessage into a synchronous function?

app.config(function($stateProvider, $urlRouterProvider) {
  var rootRef = new Firebase(some url);
  var user = rootRef.getAuth();
  chrome.runtime.sendMessage({action: 'isDrawing'},function(res) {
    if (!user) { 
      $urlRouterProvider.otherwise('/login');
    } else if (res.isDrawing === 'true') {
      $urlRouterProvider.otherwise('/draw');
    } else {
      $urlRouterProvider.otherwise('/main');
    }
  });
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100
  • 1
    Most web operations are async and that is the way you should work: *with async*. Can you explain more clearly what the actual problem is? "not jiving well with app.config" does not really tell us much :) – iCollect.it Ltd Mar 27 '15 at 09:55
  • No you cant turn it not async. Explain the actual issue – Zig Mandel Mar 27 '15 at 14:27

1 Answers1

0

The answer to your question is no, you cannot turn an asynchronous function to a synchronous one. The detailed explanation could be found here

However you can make async api more friendly by using promises. Here is an example for the storage service:

angular
    .module('core.services')
    .service('chromeStorageService', ['$q', function($q) {
        var $key = 'UniqueKey';

        this.loadState = function() {
            var deferred = $q.defer();

            chrome.storage.sync.get($key, function(data) {
                deferred.resolve(data[$key]);
            });

            return deferred.promise;
        };
    }]);

Then you can use the service like this:

storageService.loadState().then(function (state) {
    // do something with your state;
})
Community
  • 1
  • 1
sergio
  • 584
  • 7
  • 12