簡體   English   中英

在使用promise.then AngularJS之后只顯示一條消息

[英]Show only one message after foreach with promise.then AngularJS

大家好我在AngularJS中使用REST在確認按鈕中調用此函數。 保存是可以的,問題發生在成功或錯誤消息中。 如果成功,它應該在執行循環后只顯示一條成功消息,或者在任何錯誤上多次顯示錯誤消息。 如果發生錯誤,我使用了一個標志isError來獲取,但不管我做什么,“if(isError == false){”總是在循環結束之前執行。

 $scope.confirm = function () {
        var isError = false;
        var i=0;
        $scope.displayedmodalcollection.forEach(function(item) {
            i++;
            delete item.added;
            result = DataBase.update({
                id: item._id,
                endpoint: item._type
            }, item._source).$promise.then(function(response) {

            }, function(err) {
                isError = true;
                if (err.status === 500) {
                    ngToast.create({
                        className: 'warning',
                        content: String.format('Any message.', item._id)
                    });
                }
                else if (err.status === 404) {
                    ngToast.create({
                        className: 'danger',
                        content: '404 - other message'
                    });
                } else {
                    ngToast.create({
                        className: 'danger',
                        content: 'Error'
                    });
                }
            });
        });
        if (isError == false){

            ngToast.create({
                className: 'success',
                content: 'Success'
            });
        }
     };

有沒有人對此提出建議? 謝謝

您可以使用$q.all()來顯示基於所有更新解析的成功吐司

代替 :

$scope.displayedmodalcollection.forEach(function(item) {

做點什么

// map array of update promises
var updatePromises = $scope.displayedmodalcollection.map(function(item){
   // return the promise
   return DataBase.update({...}).$promise.then(function(response) {
               // success code
            }, function(err) {
               // error code
            });    
});    

$q.all(updatePromises).then(function(){
      // all promises were resolved
      ngToast.create({
                className: 'success',
                content: 'Success'
      });
});

記得在控制器中注入$ q

我不確定您希望如何處理成功的更新和錯誤,但這應該會讓您走上正確的軌道:

$scope.confirm = function() {
    var successes = 0;
    var errors = 0;
    $scope.displayedmodalcollection.forEach(function(item) {
        delete item.added;
        result = DataBase.update({
            id: item._id,
            endpoint: item._type
        }, item._source).$promise.then(function(response) {
            successes++;
            checkStatus(successes, errors);
        }, function(err) {
            errors++;
            checkStatus(successes, errors);
            if (err.status === 500) {
                ngToast.create({
                    className: 'warning',
                    content: String.format('Any message.', item._id)
                });
            } else if (err.status === 404) {
                ngToast.create({
                    className: 'danger',
                    content: '404 - other message'
                });
            } else {
                ngToast.create({
                    className: 'danger',
                    content: 'Error'
                });
            }
        });
    });
};

function checkStatus(successes, errors) {
    var isCompleted = (successes + errors) == $scope.displayedmodalcollection.length;
    var notAllFailed = successes > 0;
    if (isCompleted && notAllFailed) {
        handleSuccessToast();
    }
}

function handleSuccessToast() {
    ngToast.create({
        className: 'success',
        content: 'Success'
    });
}

問題是isError == false分支中的成功邏輯正在所有DB調用完成之前執行。 因此,它在錯誤實際發生之前可能正在運行,因此標志為false並且遵循分支。

發生這種情況是因為DB邏輯正在返回promise。 Promise不會阻止其余代碼的執行 - 它們只是推遲'then'回調中包含的邏輯,直到DB調用實際完成為止。 因此,如果您的收藏中有5個項目,則可以在實際完成任何項目之前啟動所有5個項目的數據庫調用。 關鍵是您需要讓您的成功邏輯等待,直到您知道所有數據庫承諾已經解決並且所有呼叫都已完成。 有關承諾的更多信息,請參閱此承諾指南

下面是一個示例,說明在檢查是否發生任何錯誤之前,您可以如何編寫邏輯以等待所有承諾解析:

var doneCount = 0;
var isError = false;
something.foreach(item) {
    somedblogic(item).$promise.then(function (response) {
        if (++doneCount === something.length && !isError) {
            //-- success logic here - runs one time after all db calls complete
        }
    },function (err) {
        doneCount++;
        isError = true;
        //-- rest of error logic here - runs once for each error returned
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM