2013-09-30 58 views
1

這兩個功能是我正在處理的音樂播放列表項目的控制器的一部分。在用戶選擇他的文件後,調用準備功能來檢查每個文件是否有效。完成後,調用getIDtags將ID3tags數據添加到每個文件。angularJS鏈承諾

 var preparePlaylist = function (files){ 

      var allPromises = [], 
       currentSongsListLength = $scope.songsList.length || 0; 

      $.each(files, function (index){      
       var file = files[index]; 
       file.index = index + currentSongsListLength; 
       var promiseA = FileValidator2.check(file); 
       allPromises.push(promiseA); 
       promiseA 
        .then (function (file){ 
        SharedService.addSong(file.index, file); 
       }); 
      }); 

      $q 
       .all(allPromises) 
       .then(function() {       
        console.log('Check Resolved!'); 
        console.log('SharedService updated.'); 
        getID3tags(); 
      }); 
     }; 


     var getID3tags = function(){ 
      var ID3tagsPromises = []; 

      $.each($scope.songsList, function(index){ 
       var promiseB = ID3tags.getTags($scope.songsList[index]); 
       ID3tagsPromises.push(promiseB); 
       promiseB 
        .then(function (file){ 
         SharedService.addSong(file.index, file); 
        }); 
      }); 

      $q 
       .all(ID3tagsPromises) 
       .then(function() {       
        console.log('ID3tags Resolved!'); 
        console.log('SharedService updated.');       
      }); 

     }; 

如何將2個功能/承諾(promiseA,promiseB)合併成鏈式承諾一個功能,仍然可以得到$ q.all當一切都done.Thanxs。

+0

抱歉,但問題是,還不是很清楚 –

回答

1

因此,您的文件中的每個函數都需要一個接一個地調用(對於此問題域),請嘗試此操作。

如果functionA返回一個promise並且functionB返回一個promise,那麼functionA的promise可以用來自functionB的promise來解析。

function preparePlaylist(){ 
    var finished = $q.defer(); 
    // rest of function body 
    $q.all(allPromises).then(function(){ 
     //Do whatever you need 
     finished.resolve(getID3tags()); 
    }); 
    return finished.promise; 

function getID3tags(){ 
    var finished = $q.defer(); 
    //rest of function body 
    $q.all(ID3tagsPromises).then(function(){ 
     //Do whatever you need 
     finished.resolve('Done both preparePlaylist and getID3tags'); 
    }); 
    return finished.promise; 

preparePlaylist.then(function(response){ 
    console.log(response); 
}); 

這可能需要一點調整,但它應該工作。但我沒有測試過它。希望能幫助到你!

文檔以供參考:http://docs.angularjs.org/api/ng $ Q

+1

嘿ryaan thanxs但我想我已經不能正確解釋我的自我。 2函數具有完全相同的結構(語法明智)。我想將它變成1個具有鏈接承諾的func。首先檢查文件,解決問題,然後獲取ID標籤,並只用一個$ .each解決。希望我讓自己更清楚一點。 – Amitka