嵌套承诺 - 更好的方法?

nested promises - better way?

我是一名新开发人员,正在处理一个相当复杂的场景,在该场景中,当用户保存时,可能会有锁,并且用户有机会越过锁。如果有锁,因为 REST 是无状态的,我在 PUT 上发送的对象就会丢失,所以我必须允许用户越过锁,然后再次发出放置请求。

在第二个 if 检查中,您可以看到我有一个嵌套的 promise。根据我对承诺与回调的了解,这违背了使用承诺的目的。我通读了其他一些答案,但不理解在 inner/nested 承诺中返回承诺的概念。我如何重构下面的代码以使其更符合最佳实践而不是嵌套承诺?

//the user chooses to over ride someone else's lock
  $scope.$on('forceLockAfterModalSubmit', function (e, data) {
    if (!$scope.newItemCreatedIsLocked) {
      $scope.setLockForCurrentUser();
      $scope.editMode = true;
    }
    if ($scope.newItemCreatedIsLocked) {
      service.forceLock($scope.id).then(function () {
        itemService.updateItem($scope.itemForRequestBeforeLockResponse).then(function () {
          $scope.postPUTRequestActions($scope.itemForRequestBeforeLockResponse);
        })
      }, function (err) {
        console.log(err);
      })
    }
  })

对此也很陌生,但也许这可能有用。

另一个想法是,在第一个 returns 承诺的函数中,您可能想要调用另一个函数并使用 setTimeout(function2, "insert milliseconds here") ,尽管从长远来看这会减慢速度运行 因为一旦数据准备好你就想要它......对我来说似乎很老套,但它可能是短期的绷带。

在一些相关的注释中,您可能希望将内容写成这样以帮助提高可读性。

service.then(successFunction).catch(errorFunction);

function successFunction(response) {
    if (response == "Valid Data") {
      return response;
    } else {
      console.log("Something is wrong with the success function!");
      return response;
    }

    functon errorFunction(response) {
      console.log("Error occurred in the service!");
    }

希望这对你有所帮助。

您正在混合回调和承诺,并使其变得比必须的更难。 您所有的异步函数都应该 return 一个承诺,而不是使用第二个 .then() 作为错误处理程序,您应该让 .catch() 函数处理错误。

您目前拥有的代码可以替换为

$scope.$on('forceLockAfterModalSubmit', function(e, data) {
  if (!$scope.newItemCreatedIsLocked) {
    $scope.setLockForCurrentUser();
    $scope.editMode = true;
  }
  if ($scope.newItemCreatedIsLocked) {
    service.forceLock($scope.id)
      .then(function() {
        return itemService.updateItem($scope.itemForRequestBeforeLockResponse);
      })
      .then(function() {
        return $scope.postPUTRequestActions($scope.itemForRequestBeforeLockResponse);
      })
      .catch(function(err) {
        console.log(err);
      });
  }
});

如果你想要一个更干净的解决方案,你可以声明一个函数来调用你的 itemService.updateItem$scope.postPUTRequestActions 与范围 id 你最终会得到

$scope.$on('forceLockAfterModalSubmit', function(e, data) {
  if (!$scope.newItemCreatedIsLocked) {
    $scope.setLockForCurrentUser();
    $scope.editMode = true;
  }
  if ($scope.newItemCreatedIsLocked) {
    service.forceLock($scope.id)
      .then(itemService.updateItem)
      .then($scope.postPUTRequestActions)
      .catch(function(err) {
        console.log(err);
      });
  }
});

易于理解和遵循。