1

I have this code:

 $scope.play = function (audio) {
     var deferred = $q.defer();
     api.play(audio).then(function () {
         deferred.resolve();
     }, function (err) {
         deferred.reject();
         console.log(err);
     });
     return deferred.promise;
 };

I have a array of audio that i use inside my controller and pass to $scope.play. However, using the below:

var playIndex = 0;
$scope.play(audios[playIndex]).then(function () {
    playIndex++;
    $scope.play(audios[playIndex]);
});

This works for the first two audios i have in the array of course since I am not checking the return of the second .play. How can i make this loop through all the audios array successfully?

Thanks in advance.

1
  • Wrapping existing promises in new deferrals is an anti-pattern. Your function should be $scope.play = function (audio) { return api.play(audio); }. That's it, really. Commented May 26, 2015 at 23:43

2 Answers 2

2

You can name a function passed into then and invoke it from itself recursively:

var playIndex = 0;

$scope.play(audios[playIndex]).then(function next() {
    if (++playIndex < audios.length) {
        $scope.play(audios[playIndex]).then(next);
    }
});

Demo: http://jsfiddle.net/3jx3eh8t/

Sign up to request clarification or add additional context in comments.

Comments

1

You could create a poll function that will call itself recursively when last audio promise get resolved. Pool function will call $scope.play which will increment playIndex on its success & then again call poll function which will look for the next audio to play on. You need to make sure by adding some condition before calling poll(playIndex) to get it called infinitely.

Code

(function poll(playIndex) {
    $scope.play(audios[playIndex]).then(function() {
        playIndex++;
        poll(playIndex);//here it should be call on some condition
    });
})(playIndex);

1 Comment

Thanks, can you please elaborate more as i'm not sure how to use this exactly. - Please note that the .play function takes audios[index] not just the index as you described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.