Sam
Sam

Reputation: 15771

Refactor to a Promise/A Pattern

How can I refactor this into the Promise/A pattern so that I can eliminate the timer and just handle the Promise sent back?

$scope.manageAccess = function () {
            queuedRepository.queuedItems().then(function (queuedItems) {
                if (queuedItems.length === 0) {
                    var path = globalLocation.pathname(),
                    hash = globalLocation.hashNoBang();

                    globalLocation.url(app.vroot() + "SharedSubmission/" + $scope.data.submissionVersion.id + "?path=" + path + "&hash=" + hash);
                } else {
                    console.log("Pending items in the queue... Retrying in 500ms.");
                    setTimeout(function () {
                        $scope.manageAccess();
                    }, 500);
                }
            });
        };

Queued Repository

return {
    queuedItems: function() {
        return persistentCache.list('qr'); // Return Promise
    }, ...

Upvotes: 0

Views: 79

Answers (1)

Esailija
Esailija

Reputation: 140210

function delay(ms) {
    var d = $q.defer();
    setTimeout(function(){
        d.resolve();
    }, ms);
    return d.promise;
}

$scope.manageAccess = function () {
    return queuedRepository.queuedItems().then(function (queuedItems) {
        if (queuedItems.length === 0) {
            var path = globalLocation.pathname(),
                hash = globalLocation.hashNoBang();

            return globalLocation.url(app.vroot() + "SharedSubmission/" + $scope.data.submissionVersion.id + "?path=" + path + "&hash=" + hash);
        } else {
            return delay(500).then(function(){
                return $scope.manageAccess();
            });
        }
    });
};

Upvotes: 1

Related Questions