websocket support promise

This commit is contained in:
MaysWind 2016-05-27 00:29:05 +08:00
parent 0fe73ffe73
commit 5d188da416

View file

@ -1,10 +1,10 @@
(function () { (function () {
'use strict'; 'use strict';
angular.module('ariaNg').factory('aria2WebSocketRpcService', ['$websocket', 'ariaNgSettingService', function ($websocket, ariaNgSettingService) { angular.module('ariaNg').factory('aria2WebSocketRpcService', ['$q', '$websocket', 'ariaNgSettingService', function ($q, $websocket, ariaNgSettingService) {
var rpcUrl = ariaNgSettingService.getJsonRpcUrl(); var rpcUrl = ariaNgSettingService.getJsonRpcUrl();
var socketClient = null; var socketClient = null;
var sendIdMapping = {}; var sendIdStates = {};
var getSocketClient = function () { var getSocketClient = function () {
if (socketClient == null) { if (socketClient == null) {
@ -24,18 +24,29 @@
var uniqueId = content.id; var uniqueId = content.id;
var result = content.result; var result = content.result;
if (!sendIdMapping[uniqueId]) { if (!sendIdStates[uniqueId]) {
return; return;
} }
var context = sendIdMapping[uniqueId]; var state = sendIdStates[uniqueId];
if (!state) {
return;
}
var context = state.context;
var callbackMethod = context.callback; var callbackMethod = context.callback;
state.deferred.resolve({
success: true,
context: context
});
if (callbackMethod) { if (callbackMethod) {
callbackMethod(result); callbackMethod(result);
} }
delete sendIdMapping[uniqueId]; delete sendIdStates[uniqueId];
}); });
} }
@ -52,9 +63,16 @@
var uniqueId = context.uniqueId; var uniqueId = context.uniqueId;
var requestBody = angular.toJson(context.requestBody); var requestBody = angular.toJson(context.requestBody);
sendIdMapping[uniqueId] = context; var deferred = $q.defer();
return client.send(requestBody); sendIdStates[uniqueId] = {
context: context,
deferred: deferred
};
client.send(requestBody);
return deferred.promise;
} }
}; };
}]); }]);