【问题标题】:Uploading duplicates but not sure why上传重复但不知道为什么
【发布时间】:2015-08-08 07:21:27
【问题描述】:

我有以下代码行,它们应该检索 PouchDB 中的所有文档和图像。
在这种情况下,只有两个带有图像的文档用于测试。

当我从 PouchDB 中检索所有文档时,我得到的每个文档都很好。然后应该分别上传每个文档的图像并将返回推送到$scope.qc.images,然后再发布$scope.qc。但就我而言,它两次发布 document1。

第一个帖子有document1,图片来自document1。第二个帖子有document1,图片来自document1document2。但是,document2 从未发布过。

我想在这个测试用例中发布一份文档,每个文档都有一张图片。请注意lastTask 中的提醒,这里我两次收到相同的文档:(

请看下面的代码:

 /**
     * Upload offline qcs
     */
    $scope.uploadOfflineQcs = function () {
      var token = window.localStorage.getItem('yourTokenKey');
      $scope.localQcDB.allDocs({
        include_docs: true
      }).then(function (response) {
        response.rows.forEach(function (row) {
          //this gives me each doc fine
          alert(JSON.stringify(row.doc.qc));
          //this gives me each image fine
          alert(JSON.stringify(row.doc.images));

          $scope.qc = row.doc.qc;
          $scope.images.test = row.doc.images;

          $scope.loading = $ionicLoading.show({
            content: 'Uploading QC...',
            showBackdrop: false
          });

          var promises = $scope.images.test.map(function (image) {
            var options = {
              fileKey: "image",
              fileName: "test.png",
              chunkedMode: true,
              mimeType: "image/png",
              headers: {'x-auth-token': token},
              params: {'questionId': image.questionId}
            };
            return $cordovaFileTransfer.upload(MOBILEAPP_URL + "file/upload", image.image, options);
          });

          return $q.all(promises).then(lastTask); // returns a promise for results

          function lastTask(results) {
            //this gives me same doc which is also uploaded twice.
            alert(JSON.stringify($scope.qc));

            results.forEach(function (result) {
              $scope.qc.image.push(JSON.parse(result.response));

              $scope.qc.coordinates = {
                "latitude": window.localStorage.getItem('latitude'),
                "longitude": window.localStorage.getItem('longitude')
              };

              $http({
                method: 'POST', url: MOBILEAPP_URL + 'api/forms/qualitycontrol', headers: {
                  'x-auth-token': token
                }, data: $scope.qc
              }).
                success(function (data, status, headers, config) {
                  // this callback will be called asynchronously
                  // when the response is available
                  $scope.qc = {image: []};
                  $scope.sigImg = '';
                  $scope.images.test.length = 0;
                  $scope.images.length = 0;
                }).
                error(function (data, status, headers, config) {
                  // called asynchronously if an error occurs
                  // or server returns response with an error status.
                  $scope.showAlert('error ' + status);
                }).finally(function () {
                  // Stop the ion-refresher from spinning
                  $scope.$broadcast('scroll.refreshComplete');
                });
            });
            return results; // keeping the promise chain useful
          }
        });
      }).then(function () {
        $ionicLoading.hide();
        $scope.showAlert('QC successfully saved!');
        $scope.localQcDB.destroy().then(function () {
          $scope.localQcDB = new PouchDB("offline_qcs");
        }).catch(function (err) {
          console.log(err);
        });
      }).catch(function (err) {
        console.log(err);
      });
    };

【问题讨论】:

    标签: angularjs pouchdb


    【解决方案1】:

    我不确定这是否有帮助,但您似乎没有正确使用 Promise。我推荐阅读这篇文章:"We have a problem with promises"

    两个提示有助于清理你的 Promise 用法:

    1. Angular 的$http 支持旧样式(.success.error)以及新的、承诺的样式(.then.catch)。使用承诺的风格。
    2. 不要使用forEach;使用return Promise.all(myList.map(...))

    希望对您有所帮助! :)

    【讨论】:

    • 我实际上是在链接链接中的示例,就在“所有这一切的 TLDR 是 forEach()/for/while 不是您要查找的构造。您想要 Promise。 all():" 并且不能 console.log(arrayOfResults),为什么?
    【解决方案2】:

    所以下面的代码让一切正常。

     /**
         * Upload offline qcs
         */
        $scope.uploadOfflineQcs = function () {
          var token = window.localStorage.getItem('yourTokenKey');
          $scope.localQcDB.allDocs({
            include_docs: true
          }).
            then(function (result) {
            var rows = result.rows.map(function (row) {
              var images = row.doc.images.map(function (image) {
                $scope.loading = $ionicLoading.show({
                  content: 'Uploading QC...',
                  showBackdrop: false
                });
                var options = {
                  fileKey: "image",
                  fileName: "test.png",
                  chunkedMode: true,
                  mimeType: "image/png",
                  headers: {'x-auth-token': token},
                  params: {'questionId': image.questionId}
                };
                return $cordovaFileTransfer.upload(MOBILEAPP_URL + "file/upload", image.image, options);
              });
              return $q.all(images).then(lastTask);
    
              function lastTask(results) {
                results.forEach(function (result) {
                  row.doc.qc.image.push(JSON.parse(result.response));
                });
    
                $http({
                  method: 'POST', url: MOBILEAPP_URL + 'api/forms/qualitycontrol', headers: {
                    'x-auth-token': token
                  }, data: row.doc.qc
                }).
                  success(function (data, status, headers, config) {
                    $scope.qc = {image: []};
                    $scope.sigImg = '';
                    $scope.images.test.length = 0;
                    $scope.images.length = 0;
                  }).
                  error(function (data, status, headers, config) {
                    $scope.showAlert('error ' + status);
                  }).
                  finally(function () {
                    $scope.$broadcast('scroll.refreshComplete');
                    $ionicLoading.hide();
                    $scope.showAlert('QC successfully saved!');
                    $scope.localQcDB.destroy().then(function () {
                      $scope.localQcDB = new PouchDB("offline_qcs");
                    }).catch(function (err) {
                      console.log(err);
                    });
                  });
              }
            });
            return $q.all(rows);
          });
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2022-01-26
      相关资源
      最近更新 更多