我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
我有一个factory在获取json文件时向我提供的承诺:
myapp.factory('topAuthorsFactory', function($http, $q) {
var factory = {
topAuthorsList: false,
getList: function() {
var deffered = $q.defer();
$http.get('../../data/top_10_authors.json')
.success(function(data, status) {
factory.topAuthorsList = data;
}).error(function(data, status) {
deffered.reject('There was an error getting data');
});
return deffered.promise;
}
};
return factory;
});
Run Code Online (Sandbox Code Playgroud)
在我的controller我想要json在我的控制台上显示文件的内容如下:
myapp.controller('topAuthorsController', function($scope, topAuthorsFactory) {
$scope.listAuthors = topAuthorsFactory.getList().then(function(topAuthorsList) {
$scope.listAuthors = topAuthorsList;
console.log('Testing...');
}, function(msg) {
alert(msg);
});
console.log($scope.listAuthors);
}
Run Code Online (Sandbox Code Playgroud)
但是在我的控制台中,我得到了这个:
那我怎么解决这个问题呢?为什么我在控制台中看不到"测试......"的消息?
promise angularjs angularjs-controller angularjs-factory angular-promise