我有这个代码:
$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;
};
我有一个 audio
数组,我在我的 Controller 中使用它并传递给 $scope.play
。但是,使用以下内容:
var playIndex = 0;
$scope.play(audios[playIndex]).then(function () {
playIndex++;
$scope.play(audios[playIndex]);
});
这当然适用于数组中的前两个音频,因为我没有检查第二个 .play
的返回。我怎样才能使这个循环成功地遍历所有音频数组?
提前致谢。
最佳答案
您可以命名传递给 then
的函数并从自身递归调用它:
var playIndex = 0;
$scope.play(audios[playIndex]).then(function next() {
if (++playIndex < audios.length) {
$scope.play(audios[playIndex]).then(next);
}
});
关于javascript - AngularJS Promise 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30450072/