[Vuejs]-JavaScript: Promise on recursion

1๐Ÿ‘

โœ…

You would need to:

  • return the promise (both in process as in the then callback)
  • use arrow functions when you want to have access to the same this value.

Suggested code:

methods: {
    process: function process(id) {
        return this.$http.post('controller/process', { id: id }).then((res) => {
            if (res.data.items > 0) {
                return this.process(id);
            }
        }, (data) => {
            this.$notify(data, 'danger');
            this.progress = false;
        });
    },
    run: function run($id) {
        this.busy = true;
        this.process($id).then( _ => this.busy = false);  
    }
},

It should be noted however that introducing the busy flag should not be necessary when you stick to the promise pattern. It should certainly not be used to somehow wait for the process to complete. For that purpose you should stick to the then callback system (or use the async/await syntax, which comes down to the same thing).

-3๐Ÿ‘

Use deferred:

methods: {
    process: function process(id) {
        var deferred = $q.defer();
        this.$http.post('controller/process', { id: id }).then(function (res) {
            if (res.data.items > 0) {
                this.process(id);
            } else { 
                return deferred.resolve(true);
            }
        }, function (data) {
            this.$notify(data, 'danger');
            this.progress = false;
            return deferred.resolve(true); //if not will fail promise
        });

        return deferred.promise;
    },
    run: function run($id) {

        this.busy = true;   
        this.process($id)
            .then(
                function() { //executes when resolve
                    this.busy = false;  
                },
                function() {
                    //executes when you run deferred.reject() in process method
                }
        );  

    }

},

I do it without test.

Leave a comment