Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript (Angularjs) websocket with promises?

I use Angularjs in a project. I use $q.all with multiple request from $http, It's work.

In new case, I use websocket, but I don't know how to use promises with websocket.

$http return promises, but websocket is not.

Websocket Example: (it's not real code)

I send pack id is 1000, and I reviced pack id is 2000.

websocket.send(1000);

websocket.onMessage(data) {
  if (data.id == 2000) {
    // do something
  }
}

I went to use Promises with websocket, it's possible?

like image 999
allyusd Avatar asked Aug 11 '14 04:08

allyusd


1 Answers

You could setup a basic request/response reactor and wrap that with promises.

Setting up the reactor:

var callbacks = {};
websocket.onmessage = function(event) {
  var data = angular.fromJson(event.data);
  if (angular.isDefined(callbacks[data.request_id])) {
    var callback = callbacks[data.request_id];
    delete callbacks[data.request_id];
    callback.resolve(data);
  } else {
    $log.error("Unhandled message: %o", data);
  }
};

The request function:

var requestId = 0;
$scope.getRequestId = function() {
  return requestId++;
};

$scope.request = function(data) {
  var request = {
    request_id: $scope.getRequestId(),
    data: data
  };
  var deferred = $q.defer();
  callbacks[request.request_id] = deferred;
  websocket.send(angular.toJson(request));
  return deferred.promise.then(function(response) {
    request.response = response;
    return response;
  });
};

An example use case might be:

$scope.request("My Request").then(function(response) {
  // do something with response
});

You could also make use of onerror and onclose to do $q.reject where appropriate so that websocket errors could make it back to the promise.

Here is a simple websocket echo example using the above technique: http://plnkr.co/edit/ORSqXz07I9cLspZQg1iM?p=preview

like image 158
potatosalad Avatar answered Oct 03 '22 16:10

potatosalad