能否使用多个.then函数?AngularJS链式调用报错求助
问题分析与代码修正
嘿,我帮你找到了代码崩溃的原因,这就给你拆解并修正:
核心错误点
你的代码崩溃主要是两个问题导致的:
- 语法错误:在
$scope.get_list().then(...)后面多了个逗号,直接破坏了代码的语法结构,这是网站崩溃的直接原因。 - Promise调用逻辑错误:你直接调用了
$scope.get_this_list()和$scope.get_that_list(),这会让两个函数立即执行,而不是作为Promise的回调等待前一个异步操作完成后再执行。
修正后的完整代码
我已经把错误部分修正,同时保留了你的原有业务逻辑:
// list 1 $scope.get_this_list = function () { return SharedFunctions.issuePOSTOBJCmd(url + 'get_list_1' , {}) .then(function (response) { $scope.list_one_options = response.data; }, function (error) { $scope.display_error = true; $scope.display_message = 'HTTP ERROR occured. Please check with Web/Dev Admin ' + error; }); }; // list 2 $scope.get_that_list = function () { return SharedFunctions.issuePOSTOBJCmd(url + 'get_list_2' , {}) .then(function (response) { $scope.list_two_options = response.data; }, function (error) { $scope.display_error = true; $scope.display_message = 'HTTP ERROR occured. Please check with Web/Dev Admin ' + error; }); }; // 修正后的链式调用:去掉多余逗号,传递函数引用而非直接执行 $scope.get_list() .then($scope.get_this_list) .then($scope.get_that_list);
额外优化建议
如果你的两个下拉框请求不需要严格按顺序执行(比如互相没有依赖),可以用AngularJS的$q.all()让它们并行发起,提升加载效率:
$scope.get_list() .then(function() { // 同时发起两个请求,等全部完成后再继续 return $q.all([ $scope.get_this_list(), $scope.get_that_list() ]); });
注意:要确保$scope.get_list()本身返回一个Promise对象,这样才能正常进行链式调用哦。
内容的提问来源于stack exchange,提问作者Celestialchippy
相关产品推荐
相关产品推荐

