【问题标题】:How to run lastTask after forEach如何在 forEach 之后运行 lastTask
【发布时间】:2023-04-05 08:29:01
【问题描述】:

我有一组图像,我对其进行迭代并将每个图像上传到远程服务器。上传文件后,我使用结果来获取文件名并推送到另一个数组。

我遇到的问题是并非所有结果都被推送到数组中。我正在尝试构建一个包含所有上传图像结果的数组。以下代码在forEach 循环完成之前执行lastTask:

    /**
     * Upload picture
     */
    $scope.upload = function () {

      var token = window.localStorage.getItem('yourTokenKey');
      var defer = $q.defer();
      var promises = [];

      var options = {
        fileKey: "image",
        fileName: " test.png",
        chunkedMode: true,
        mimeType: "image/png",
        headers: {'x-auth-token': token}
      };

      function lastTask() {
        alert(promises);
        $scope.images = [];
        $scope.hide();
        $scope.showAlert();
        $scope.putQc();
        alert('finish').then(function () {
          defer.resolve();
        });
      }

      angular.forEach($scope.images, function (image) {
        $cordovaFileTransfer.upload("http://server.com/file/upload", image, options).then(function (result) {
          // Success!
          promises.push(result.response + '.jpg');
          alert(JSON.stringify(result));
          console.log("SUCCESS: " + JSON.stringify(result.response));
          // Error
        }, function (err) {
          alert(JSON.stringify(err));
          console.log("ERROR: " + JSON.stringify(err));
          // constant progress updates
        }, function (progress) {
          $scope.show();
        });
      });

      $q.all(promises).then(lastTask);

      return defer;
};

【问题讨论】:

    标签: javascript angularjs cordova ionic-framework promise


    【解决方案1】:

    如果我是正确的,你的promises 数组就是问题所在,而不是推动来自$cordovaFileTransfer.upload 的承诺,而是推动你得到的结果 string。

    第二个问题,我认为你在做的是承诺anti-pattern,这里不需要$q.defer()。

    (第三,可能无关紧要,JSON.stringify 不是真的需要,希望alert 是你自己定义的)

    我会改写为:

    /**
     * Upload picture
     */
    $scope.upload = function () {
    
      var token = window.localStorage.getItem('yourTokenKey');
      var promises = [], results;   //CHANGED
    
      var options = {
        fileKey: "image",
        fileName: " test.png",
        chunkedMode: true,
        mimeType: "image/png",
        headers: {'x-auth-token': token}
      };
    
      function lastTask() {
        alert(results);   //CHANGED
        $scope.images = [];
        $scope.hide();
        $scope.showAlert();
        $scope.putQc();
        return alert('finish');   //CHANGED
      }
    
      promises = $scope.images.map(function (image) {   //CHANGED
        return $cordovaFileTransfer.upload("http://server.com/file/upload", image, options).then(function (result) {   //CHANGED
          // Success!
          results.push(result.response + '.jpg');   //CHANGED
          alert(JSON.stringify(result));
          console.log("SUCCESS: " + JSON.stringify(result.response));
          // Error
        }, function (err) {
          alert(JSON.stringify(err));
          console.log("ERROR: " + JSON.stringify(err));
          throw err;
          // constant progress updates
        }, function (progress) {
          $scope.show();
        });
      });
    
      return $q.all(promises).then(lastTask);   //CHANGED
    
    };
    

    【讨论】:

    • 如果您将错误函数保留在那里,您应该重新抛出错误,以便q.all 正确失败。否则,您的错误处理程序将运行,并且承诺链成为已解决的承诺(解析值为 undefined — 错误处理程序的返回值)。
    • 不知道为什么,但这仍然存在于 $scope.show();并且从不运行 lastTask()
    • 可能是因为所有的承诺都没有解决......你能检查一下是否所有的图片都上传了,但仍然没有调用 lastTask 吗?
    • 所有图片正在上传中。只是从不执行 lastTask。
    • @fpena06 添加错误侦听器 t0 $q.all(..,可能是发生了一些错误而没有看到...
    【解决方案2】:

    问题是你没有将承诺推入你的承诺数组。您(最终)将正常值推送到数组中,但不是在您对空或接近空的数组运行 $q.all 之前。

    $scope.upload = function() {
    
        var token = window.localStorage.getItem('yourTokenKey');
        var promises = [];
    
        var options = {
            fileKey: "image",
            fileName: " test.png",
            chunkedMode: true,
            mimeType: "image/png",
            headers: {
                'x-auth-token': token
            }
        };
    
        function lastTask(results) {
            alert(results);
            $scope.images = [];
            $scope.hide();
            $scope.showAlert();
            $scope.putQc();
            return results; // keeping the promise chain useful
        }
    
        angular.forEach($scope.images, function(image) {
            var promiseForUpload = $cordovaFileTransfer.upload("http://server.com/file/upload", image, options).then(function(result) {
                console.log("SUCCESS: " + JSON.stringify(result.response));
                return result.response + '.jpg'; // this will be the promised value
            }, function(err) {
                console.log("ERROR: " + JSON.stringify(err));
                throw err; // re-throwing the error so the q.all promise is rejected
            }, function(progress) {
                $scope.show();
            });
            promises.push(promiseForUpload);
        });
    
        return $q.all(promises).then(lastTask); // returns a promise for results
    
    };
    

    老实说,虽然我会完全摆脱中级的东西:

    $scope.upload = function() {
    
        var token = window.localStorage.getItem('yourTokenKey');
    
        var options = { /* stuff */ };
    
        function lastTask(results) { // I wouldn't bake this into the $scope.upload, but do it as a result of calling $scope.upload (i.e. with .then).
            alert(results);
            $scope.images = [];
            $scope.hide();
            $scope.showAlert();
            $scope.putQc();
            return results; // keeping the promise chain useful
        }
    
        var promises = $scope.images.map(function(image){
            return $cordovaFileTransfer.upload("http://server.com/file/upload", image, options);
        });
    
        return $q.all(promises).then(lastTask); // returns a promise for results
    
    };
    

    最后,如果这个函数应该返回一个 Promise,那么无论在哪里使用它都要确保添加错误处理(例如,在链的末尾使用 .catch)。如果这个函数应该是 Promise 链的末尾(例如,仅由单击按钮触发,并且没有任何响应),那么您需要将 catch 添加到 $q.all(promises).then(lastTask) 的末尾。不要让静默错误发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2019-11-29
      相关资源
      最近更新 更多