【问题标题】:$q.all() performing synchronously not asynchronously$q.all() 同步执行而不是异步执行
【发布时间】:2019-01-03 18:25:55
【问题描述】:

我正在开发一个应用程序来从我的 API 服务器检索数据,将其与新数据进行比较,然后将新数据(如果不存在)推送到 API 服务器。目前,我正在研究使用 $http、promises 和 $q.all() 检索服务器上现有数据的功能。当我将所有承诺推送到一个数组然后使用 $q.all() 时,它会同步触发并且不会等待承诺解决。

我已经完成了,据我所知,在我想要异步运行的所有操作中都输入了返回值。我也阅读了许多有类似问题的帖子,并进行了这些调整,但没有成功。

这是来自 fileData 服务的相关代码:

var apiPromise = function (url) {
    var deferred = $q.defer();
    $http.get(url)
        .then(function (result) {
            deferred.resolve(result.data);
            return;
        });
    return deferred.promise;
};

this.GetExistingStudentTest=function(studentid){
    return apiPromise('http://localhost:65196/api/PS/GetStudentTests?studentid=' + studentid + '&testid=2')
};

this.GetExistingStudentTestScores = function (testid) {
    return apiPromise('http://localhost:65196/api/PS/GetStudentTestScore?testid=' + testid)
};

并且正在使用的控制器的代码是:

$scope.previewUpload = function () {
    var promises = [];
    for (var i = 0; i < $scope.students.count; i++) {
        var student = $scope.students.students[i];
        promises.push(fileData.GetExistingStudentTest($scope.students.students[i].studentId)
            .then(function (data) {
                for (var j = 0; j < data.length; j++) {
                    var prevTest = {
                        testId: data[j].id,
                        studentId: student.studentId,
                        rawDate: data[j].test_date.substr(5, 2)+data[j].test_date.substr(2,2),
                        date: data[j].test_date,
                        testGradeLevel: data[j].grade_level,
                        scaleScores: {}
                    };
                    promises.push(fileData.GetExistingStudentTestScores(prevTest.testId)
                        .then(function (scoreData) {
                            console.log(scoreData);
                            for (var k = 0; k < scoreData.length; k++) {
                                switch (scoreData[k].testscoreid) {
                                    case "1":
                                        prevTest.scaleScores.english = scoreData[k].numscore;
                                        break;
                                    case "2":
                                        prevTest.scaleScores.math = scoreData[k].numscore;
                                        break;
                                    case "3":
                                        prevTest.scaleScores.reading = scoreData[k].numscore;
                                        break;
                                    case "4":
                                        prevTest.scaleScores.science = scoreData[k].numscore;
                                        break;
                                    case "5":
                                        prevTest.scaleScores.writing = scoreData[k].numscore;
                                        break;
                                    case "6":
                                        prevTest.scaleScores.composite = scoreData[k].numscore;
                                        break;
                                    case "451":
                                        prevTest.scaleScores.ELA = scoreData[k].numscore;
                                        break;
                                    case "452":
                                        prevTest.scaleScores.STEM = scoreData[k].numscore;
                                        break;
                                }
                            }
                            $scope.tests.previous.tests.push(prevTest);
                            $scope.tests.previous.count++;
                            return scoreData;
                        })
                    );
                }
                return data;
            })
            );

    }



    $q.all(promises).then(function () {
        console.log('Completed Test Retrieval');
        for (i = 0; i < $scope.tests.refined.count; i++) {
            console.log($scope.tests.refined.tests[i]);
            console.log($scope.tests.previous)
            for (j = 0; j < $scope.tests.previous.count; j++) {
                console.log($scope.tests.previous.tests[j]);
                if ($scope.tests.previous[j].studentId === $scope.tests.refined[i].studentId && $scope.tests.previous[j].rawDate === $scope.tests.refined[i].rawDate) {
                    console.log('Match');
                }
            }
        }

    });

    $scope.validateTests = true;
};  

我需要看到的是测试分数返回,测试被推送到正确的数组,然后 $q.all() 解析以允许比较新数据和现有数据。实际发生的情况是,当内部 promise 被解析时,$q.all() 解析并且嵌套的 for 循环没有运行,因为数组中没有值。

【问题讨论】:

  • 这段代码真的很难读。我建议研究一种更实用的方法。更重要的是,你让你的客户做的太多了。如果客户端只是发送它的数据,这会变得更简单,让服务器找出需要更新的数据。
  • @Pytth 同意。也就是说,部分功能是允许用户确定应该上传什么,这只会对匹配提出建议,而不是严格排除匹配或不匹配的内容。不幸的是,从外部来源输入的数据通常得不到很好的照顾,而且无法知道每种情况下的重复数据是什么。
  • 那些for 循环可能存在关闭问题。见JavaScript closure inside loops – simple practical example
  • 我遇到了同样的问题。在将承诺推送到数组之前,我使用“new Promise()”修复了它。
  • apiPromise 函数是一种延迟反模式,如果 API 返回错误,它将挂起 $q.defer。见Is this a “Deferred Antipattern”?

标签: angularjs angular-promise


【解决方案1】:

首先,我将首先摆脱defer,我认为您不需要它。 $http 返回一个承诺,所以你可以做到这一点。请阅读这篇文章,它改变了游戏规则! https://www.codelord.net/2015/09/24/%24q-dot-defer-youre-doing-it-wrong/

var apiPromise = function (url) {
    return $http.get(url).then(function (result) {
       return result.data;
    });
};

其次,您不应该在 $q 之外对可能尚未解析的数据执行代码。您要么需要嵌套该逻辑,要么编写一个函数

// get all tests
var tests = students.map(function(s){
    return fileData.GetExistingStudentTest(s.studentId)
});

// wait for tests to resolve
$q.all(tests).then(function(resolvedTests){
   var transformedTests = // transform logic
   // get all test scores
   var testScores = transformedTests.map(function(t){
       return fileData.GetExistingStudentTestScores(t.testId);
   });
   // wait for test scores to resolve
   $q.all(testScores).then(function(resolvedTestScores){
      // you now have all the tests and test scores resolved...
      processTests(transformedTests,resolvedTestScores);
   });

});

【讨论】:

  • 这是钱!谢谢你的帮助。从来没有将逻辑包装在 then 函数中,但我不知道为什么。
猜你喜欢
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 2021-12-07
  • 2012-02-05
  • 2020-04-14
  • 2016-02-13
相关资源
最近更新 更多