javascript - Angular 中同一方法中的多个 post 请求

标签 javascript angularjs asynchronous synchronous

        $scope.observer_vel_data = function(){ 
        $scope.showOverlay('loadRefPubVel'); 
        $http({
            //First http post request
            method:'POST',
            url:'/api/observer_vel_data', 
            data:$scope.payload_array,
        }).then(function successCallback(response){
            console.log('API Endpoint: vel data success!'); 
            //Second post request is made in the method call below
            $scope.sentiment_var = $scope.observer_send_sentiment();
            $scope.vel_var = response.data.velocity1;
        }, function errorCallback(response){
            // console.log(response); 
            $scope.addAlert({
                type: 'danger',
                msg: 'API call failed' 
            });
        }).finally(function(){
            console.log("hello");
            console.log($scope.sentiment_var);
            //graph is rendered
            $scope.update_velocity($scope.vel_var,$scope.sentiment_var);
            $scope.hideOverlay('loadRefPubVel'); 
        });
    };

所以我试图渲染一个使用来自两个不同且独立的发布请求的数据的图表。但是,在第二个 post 请求的数据到达之前调用 graph 命令。我怎样才能解决这个问题 ?发出发布请求并渲染图形的命令在发布的代码中作为注释提到。

        $scope.observer_send_sentiment = function (){  
        // $scope.showOverlay('loadRefSentiment');
        var data = { 
            "angularGroups":$scope.groups
        };
        // console.log(data);
        $http({
            method:'POST',
            url:'http://localhost:9612/sentiment_velocity',
            data:data
        }).then(function successCallback(response){
            var data = response.data;
            var json_obj = JSON.parse(data.replace(/\'/g,'"'));
            var sentiments = json_obj["sentiments"];
            // console.log(sentiments);
            $scope.update_sentiment(sentiments); 
            console.log(sentiments);
            return sentiments;
        }, function errorCallback(response){
            var errmsg = response.statusText; 
            console.log(response); 
            $scope.addAlert({
                type: 'danger',
                msg: 'API call failed (sentiment basic)' + errmsg,  
            });
        }).finally(function(){
            // $scope.hideOverlay('loadRefSentiment');
        });
    };

最佳答案

如果我理解正确的话,您希望finally(...)中的代码仅在第二个请求结束后执行。

为了强制执行此操作,您需要链接 HTTP 请求 promise ,这意味着您需要从第一个请求的成功处理程序返回第二个 HTTP 请求的 promise 。您的代码应该或多或少像这样:

$scope.observer_vel_data = function(){ 
    $scope.showOverlay('loadRefPubVel'); 
    $http({
        method:'POST',
        url:'/api/observer_vel_data', 
        data:$scope.payload_array,
    }).then(function successCallback(response){
        console.log('API Endpoint: vel data success!');
        $scope.vel_var = response.data.velocity1;
        return $scope.observer_send_sentiment();

    }).catch(function errorCallback(response) {
        //This catch will handle errors from both HTTP requests
        $scope.addAlert({
            type: 'danger',
            msg: 'API call failed' 
        });
    })
    .finally(function(){
        console.log("hello");
        console.log($scope.sentiment_var);
        //graph is rendered
        $scope.update_velocity($scope.vel_var,$scope.sentiment_var);
        $scope.hideOverlay('loadRefPubVel'); 
    });
};

$scope.observer_send_sentiment = function() {
    return $http({...}).then(function(response) {
        //process the response
        ...
        $scope.sentiment_var = parsedResponseData;
    });
};

请注意,无论是否发生错误,finally 回调都将始终执行。如果您希望其中的某些内容仅在未遇到错误时执行,请添加另一个 .then(function() {...})

编辑:既然我们可以看到 observer_send_sentiment 的作用,那么您坚持使用 .then(function successCallback() {...}, function errorCallback 可能是有意义的() {...}) 语法,并为每个请求保留单独的错误回调。请记住,如果您添加另一个 then block ,并且您希望 Promise 链中出现错误,以防止进一步执行 .then(function() {...}) block ,您应该在两个 errorCallback 的末尾添加 return $q.reject(response)。不使用 .then(function successCallback() {...}, function errorCallback() {...}) 语法在错误回调中使用 q.reject 会渲染 promise 已解决,而不是被拒绝

关于javascript - Angular 中同一方法中的多个 post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43263719/

相关文章:

angularjs - 是否可以同时在另一个服务中注入(inject)一个服务,反之亦然?

javascript - 如何使 Nodejs 调用同步然后我可以轻松使用它?

javascript - 多次异步调用后的回调方法

java - 在我的示例中,这个异步调用是如何工作的

javascript - 返回两种颜色相互兼容性的算法

javascript - 覆盖 setInterval

javascript - ng-repeat 内计数不增加

javascript - javascript 数组按日期的基本报告?

javascript - 使用 Angularjs 在 URL 中存储 View 状态

javascript - 从查询参数中获取所有范围变量