我正在学习angularjs的承诺,并希望在我的代码中实现。我试图在对象初始化之前调用的函数中使用promise。这是一个代码
$scope.turnOffLocalAudio = function () {
if ($scope.currentCall) {
if ($scope.currentCall.chat) {
$scope.currentCall.chat.offLocalAudio(false);
}
}
}
使用承诺实施更新我的问题
app.controller('videoChat', function ($rootScope, $scope,$q) {
var deferred = $q.defer();
$scope.invite = function () {
// some variable ...
var chat = new Chat(function uiCallback(action, options) {
// other methods ...
if (action === "peer.call.localstream") {
_displayMessage("Starting local stream");
_findElement('#myVideo').prop('src', URL.createObjectURL(options.payload));
_findElement('#myVideo').css('display', 'inline');
deferred.resolve();
}
});
$scope.currentCall = {
roomId: roomId,
chat: chat,
opponentId: String($scope.currentPatientId),
};
chat.connectSocket(remoteSocket, peerURL, id, roomId);
};
$scope.changeLocalVideoStream = function () {
var promise = deferred.promise;
promise.then(function (result) {
if ($scope.currentCall) {
if ($scope.currentCall.chat) {
$scope.currentCall.chat.toggleLocalWebCam($scope.showLocalVideo);
}
}
}, function (reason) {
$log.error("unable to turn off local camera");
});
}
答案 0 :(得分:0)
你想要的是一些返回承诺的函数。我把它命名为getCurrentCall。
function getCurrentCall() {
var deferred = $q.defer();
if (!$scope.currentCall) {
$scope.currentCall = 'foo';
}
deferred.resolve();
return deferred.promise;
}
然后你在turnOffLocalRadio函数中执行此操作:
$scope.turnOffLocalAudio = function() {
getCurrentCall().then(function() {
if ($scope.currentCall.chat) {
$scope.currentCall.chat.offLocalAudio(false);
}
}, function() {
// unable to get CurrentCall
});
};