我有以下代码:
someService.fnReturnsPromise()
.then(function () {
return someService.fnReturnsAnotherPromise(someArg);
})
.then(function (resultsOfSecondFn) {
// do stuff with results
});
Run Code Online (Sandbox Code Playgroud)
我觉得这应该有效; 然而,resultsOfSecondFn实际上并不是结果,而是我回来的承诺本身.为了让它按照我想要的方式工作,我必须这样做:
someService.fnReturnsPromise()
.then(function () {
return someService.fnReturnsAnotherPromise(someArg);
})
.then(function (promiseReturn) {
promiseReturn.then(function (results) {
// do stuff with results
});
});
Run Code Online (Sandbox Code Playgroud)
这是伪代码fnReturnsAnotherPromise:
someService.fnReturnsAnotherPromise = function (arg1) {
return anotherService.anotherFnThatReturnsPromise(arg1);
};
Run Code Online (Sandbox Code Playgroud)
所以真的,它只是一个额外的层,但承诺是以任何一种方式返回.代码anotherFnThatReturnsPromise是一些简单的范例$q.defer(),return dfd.promise有些resolve()是s.
我已经使用了node.js q库,最后有一个.done()函数可以在最后调用,无论成功与否.
我研究但找不到,有人能指出正确的方向吗?
我有一个工厂方法有$ http(异步任务),所以我使用$ q promise并发生以下错误TypeError: object is not a function@line:return $ q(funtion ....)
使用Promise API编写:
service.fetch = function(query) {
return $q(function(resolve, reject){
$http({ url: srcset[query], method: 'GET'}).success(function(db){
resolve(db);
});
});
};
Run Code Online (Sandbox Code Playgroud)
但如果使用Deferred API编写:
service.fetch = function(query) {
var deferred = $q.defer();
$http({ url: srcset[query], method: 'GET'}).success(function(db){
deferred.resolve(db);
});
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
它工作正常
我写的完全如https://docs.angularjs.org/api/ng/service/ $ q中所述
任何人都可以指出我哪里出错了.
Angular的新手,可能使用了错误的承诺.我有一个工厂回复承诺:
.factory('myData', ['$http', '$q', function($http, $q) {
var deferred = $q.defer();
$http.get('/path/to/endpoint')
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err.what())
});
return deferred.promise;
}])
Run Code Online (Sandbox Code Playgroud)
现在,如果我在某处注入我的工厂,我可以使用承诺:
.controller('myController', ['$scope', 'myData', function($scope, myData) {
myData.then(function(result) {
$scope.data = result;
});
}]);
Run Code Online (Sandbox Code Playgroud)
这很好,但我开始myData在几个地方使用,我不想.then在我使用数据的每个指令和控制器中写一个新的.在承诺解决后我不再关心它了,有没有办法让它myData返回一个承诺,如果它没有得到解决但只是在它完成解析后返回结果?
换句话说,可以myData简单地解决.then result后,或者我.then每次都要写一个新的?
我正在尝试实施基本的安全检查,以根据用户的权限集阻止用户访问某些状态:
'use strict';
var autoExecApp = angular.module("myApp", ['ui.router']);
autoExecApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$stateProvider
.state('index', {
url: '/index',
templateUrl: 'partials/index.html'
})
.state('permission', {
url: '/permission',
templateUrl: 'partials/permissions.html'
});
}]);
autoExecApp.run(['$rootScope', '$state', '$userRoles', function($rootScope, $state, $userRoles) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
event.preventDefault(); // prevent page from being loaded anyway
$userRoles.hasPermissions(toState.name).then(function(data) {
var result = data === "true";
if (!result) {
$state.go('permission');
}
else {
$state.go(toState.name, toParams ,{notify:false});
}
});
});
}]);
Run Code Online (Sandbox Code Playgroud)
现在的问题是我的状态改变发生在一个 promise 内。我很乐意让它同步 - 在这种情况下确实应该如此,但我很困惑为什么它不能异步工作。
如果我移动event.preventDefault()承诺的内部,它会起作用。但是状态变化分 2 …
根据AngularJS,我$http通过我的控制器的服务调用返回undefined?
这里似乎有什么问题?我试图返回调用的数据,但一旦传递给控制器,数据变得不确定?
JavaScript的
var myStore = angular.module('myStore', [])
.controller('StoreController', ['$scope', 'dataService', function ($scope, dataService) {
$scope.products = dataService.getData();
}])
.service('dataService', ['$http', function($http) {
this.getData = function() {
$http.get('assets/scripts/data/products.json')
.then(function(data) {
return data;
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="content">
<ul>
<li ng-repeat="product in products.products">{{product.productName}}</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我的理解是$http,$q和$resource所有的回报承诺,但我想我已经覆盖了与.那么.
我正在尝试测试一个Angular服务,它有2个依赖项,一个在$ q上,另一个在'myService'上,它也依赖于$ q.
(function() {
'use strict';
angular.module('myModule').factory('myService', [
'$q',
'apiService',
function($q, apiService) {
var data = null;
function getData() {
var deferred = $q.defer();
if (data === null) {
apiService.get('url').then(function(result) {
data = result;
deferred.resolve(data);
}, function() {
deferred.reject();
});
} else {
deferred.resolve(data);
}
return deferred.promise;
}
return {
getData: getData
};
}
]);
})();
Run Code Online (Sandbox Code Playgroud)
我开始编写一个Jasmine测试,如下所示,但是有问题嘲笑$ q.我想将$ q的真实版本而不是模拟版本注入'myService'和'apiService',但我不知道如何实现这一目标.
'use strict';
describe('My service', function() {
var qSpy, apiServiceSpy;
beforeEach(module('myModule'));
beforeEach(function() {
qSpy = jasmine.createSpyObj('qSpy', ['defer']);
apiServiceSpy = jasmine.createSpyObj('apiServiceSpy', ['get']); …Run Code Online (Sandbox Code Playgroud) 我想更新我在工厂中保存的全局数组中的一些值.我使用get方法获取数据,但设置函数以某种方式不起作用,并且数组中的值不会更新.我错过了什么?
.factory('messageList', function () {
var Messages =
[
{ "title":"Cash in", "icon":"ion-social-euro",
"dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0",
"category": "financial", "active": "true"
},
{ "title":"Sales orders", "icon":"ion-social-euro",
"dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0",
"category": "sales", "active": "true"
}
]
return {
get: function() {
return Messages;
},
set: function(title, key, newValue) {
for (var i = 0; i < Messages.length; i++) {
if(Messages[i].title == title){
Messages[i].key = newValue;
}
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
这是我尝试更新控制器中的值的方法:
messageList.set("Sales orders","dailyValue", $Scope.sum);
Run Code Online (Sandbox Code Playgroud) 我没有能力更改端点,如果失败,它将返回200 OK响应,其中包含不同的数据.如何让它运行错误函数(then来自promise 的第二个函数)?
我的服务:
self.getData = function() {
return $http.get('/api/controller/action').then(function(x) {
//This will be run even on failure. How can I call....
return x.data;
}, function(x) {
//......here, from the front-end, so that, the 2nd function in
//inside the 'then' in the controller is run.
//This code will currently never run as it never fails server side.
return x;
});
};
Run Code Online (Sandbox Code Playgroud)
控制器:
MyService.getData().then(function(x) {
//Success
}, function(x) {
//Failure
});
Run Code Online (Sandbox Code Playgroud) 我非常熟悉如何$q工作,我在angularjs中使用它等待单个promises解决和多个promise来解决$q.all().
问题是我不确定它是否可以这样做(如果它可以正常工作):我可以等待一个单一的承诺来解决,但是当我的所有承诺也解决时也运行一些代码......成功之后个别承诺的回调已经完成......例如:
var promises = [];
for(i=1, i<5, i++){
var singlePromise = SomeSevice.getData();
promises.push(singlePromise);
singlePromise.then(function(data){
console.log("This specific promise resolved");
});
}
// note: its important that this runs AFTER the code inside the success
// callback of the single promise runs ....
$q.all(promises).then(function(data){
console.log("ALL PROMISES NOW RESOLVED"); // this code runs when all promises also resolved
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是否像我认为的那样有效,或者是否存在一些奇怪的异步,不确定的结果风险?
angular-promise ×10
angularjs ×10
javascript ×8
promise ×4
angular-http ×1
asynchronous ×1
chaining ×1
jasmine ×1
q ×1
unit-testing ×1