Angular Promise未同步运行
Angular Promise not running synchronously
我的javascript控制器中有以下代码。当从视图中独立和异步调用时,这些函数可以工作。然而,我想在页面加载时同步调用它们,因为在调用第二个函数时使用了第一个函数的返回值
$scope.function1= function () {
$http({
url: '/Class/method1/',
method: 'GET'
}).success(function (data) {
$scope.mygrid= data.data;
$scope.myvalue= $scope.mygrid[0];
});
};
$scope.function2= function () {
$http({
url: '/class/method2/',
method: 'POST',
params: { myValue: $scope.myvalue }
}).success(function (data) {
$scope.myValue2 = data.data;
});
};
var initialize = function () {
var defer = $q.defer();
defer.promise
.then(function() {
$scope.function1();
})
.then(function() {
$scope.function2();
})
defer.resolve();
};
initialize();
在第二次调用中,$scope.myvalue为null。数据已经从函数1返回,所以我唯一能想到的是函数2被调用得太早了。有指针吗?:-)
initialize
中的promise同步运行。而$http
请求没有。这导致在不等待$scope.function1
中的promise解析的情况下调用$scope.function2
。
应该是
$scope.function1= function () {
return $http...
};
$scope.function2= function () {
return $http...
};
在这种情况下,延迟承诺是反模式的,initialize
应该如此简洁:
var initialize = function () {
return $scope.function1().then(function() {
return $scope.function2();
})
};
$http({
url: 'url',
method: 'GET'
})
这也是一种承诺,因此它将运行异步。
$scope.function1= function () {//3rd step
$http({
url: '/Class/method1/',
method: 'GET'
}).success(function (data) {
$scope.mygrid= data.data; //this run as asyn after response recived
$scope.myvalue= $scope.mygrid[0];
});
};
$scope.function2= function () { //5th step
$http({
url: '/class/method2/',
method: 'POST',
params: { myValue: $scope.myvalue }
}).success(function (data) {
$scope.myValue2 = data.data; //this run as asyn after response recived
});
};
var initialize = function () {
var defer = $q.defer();
defer.promise
.then(function() {
$scope.function1(); //2nd step
})
.then(function() {
$scope.function2(); //4th step
})
defer.resolve(); //1st step
};
initialize();
相关文章:
- 与运行长作业(javascript,node.js)的第三方API同步的最佳实践
- strongloop script.js run find in before delete方法:如何同步运行异步方法
- Javascript.同步运行多个承诺
- javascript如何成为一种同步语言并在浏览器和node.js环境中异步运行
- 有没有可能以某种方式用Promises运行同步循环
- Angular Promise未同步运行
- 如何使用Grunt异步运行2同步任务
- 如何确保包含多个$.ajax调用的函数完全同步运行,并允许在执行时重新绘制浏览器
- 谷歌浏览器同步存储“获取”命令运行什么顺序
- 在 ES6 中同步加载其名称在运行时确定的模块
- 让 Frisby.js 测试同步运行
- 灯光开关加载所有数据或同步运行异步方法
- 运行 AJAX 异步时文档类型标记的“意外输入结束”,但在同步时则不然
- 包含功能的同步运行
- 如何将异步进程更改为作为同步进程运行
- 如何在Javascript node.js中同步运行parseString()函数
- 在JavaScript中的异步函数末尾运行同步函数
- 如何将对象传递给 gulp 任务以便能够同步运行该任务
- 为什么流行的JavaScript运行时不能处理看起来像同步的异步脚本?
- 启动Javascript的时间间隔是非同步的,每次运行三次后停止