2016-06-20 116 views
0

我有一個視頻對象的列表,每個對象都有一個鏈接和其他幾個屬性。我建立了一個循環,通過這個列表並通過他們的鏈接上傳這些視頻,我目前使用的服務不支持一次上傳多個視頻,我需要等待第一個視頻上傳後需要第二次上傳...等

這裏的負責此代碼:

$scope.upload = function(){ 
    $scope.videoList.forEach(function(video){ 
     video.state = "Downloading" 
     $scope.msg = "The video is downloading" 
    $http.post("/download",{link : video.link,title : video.title}).then(function(resp){ 
     $scope.msg = "The video has been downloaded on the server, it will now start uploading" 
     var filen = resp.data["fn"] 
     var title = resp.data["title"] 
     video.state = "Uploading" 
     $http.get("/uploadVid?file=" + filen +"&title=" + title).then(function(resp){ 
     if (resp.data == "0002"){ 
     alert("You didn't authorize the App yet, please authorize it to be able to use it .") 
     } 
     if (resp.data == "000X"){ 
     alert("An error occured, please retry .") 
     } 
     else{ 
     $scope.msg = "the video uploaded, here's the link: " + resp.data 
     video.state = "Done" 
     video.link = resp.data 
     } 
     }) 
    }) 

    }) } 

這裏發生什麼,是每個視頻我們下載它的服務器上,一旦它的下載,它的上傳到視頻託管服務(在我們的情況下是YouTube)。這應該可以正常工作,但由於$http服務調用的異步性質,它們都在同一時間開始下載並同時上傳。

該循環不會等待iteraion完成並直接進入下一次迭代。我希望這是同步的,視頻應該被下載並逐一上傳。我寧願不使用Promises Interface,我很匆忙,而且我對它們的瞭解不多。如果你確實請儘可能多地解釋它。

+1

你*不*想讓請求*同步*。你*要*想讓他們*順序*。 –

+0

您已經在您的代碼中使用Promises,http.post返回一個承諾,並在該承諾解決時調用您的函數。 –

+0

@ T.J.Crowder如何使它們連續,並且有什麼區別,你能解釋一下嗎? – DeltaWeb

回答

3

不要想要使請求同步。你想讓他們順序。 (A 同步 Ajax請求是一個最多可容納JavaScript的UI線程  —,通常瀏覽器的UI,至少該選項卡  —等待AJAX​​操作完成之內。這是件糟糕的用戶體驗,否則他們順序只是意味着一個接一個地做,例如按順序而不是平行)。

通常的做法是跟蹤你正在使用哪一個,做你的處理,然後完成處理那一個,繼續下一個;看評論:

$scope.upload = function() { 
    // Grab the array and start with index = 0 
    var videos = $scope.videoList; 
    var index = 0; 
    if (videos.length) { 
     // Start the process 
     next(); 
    } 

    // Our handler for each video 
    function next() { 
     // Get the video 
     var video = videos[index]; 
     video.state = "Downloading" 
     $scope.msg = "The video is downloading" 
     $http.post("/download", { 
      link: video.link, 
      title: video.title 
     }).then(function(resp) { 
      $scope.msg = "The video has been downloaded on the server, it will now start uploading" 
      var filen = resp.data["fn"] 
      var title = resp.data["title"] 
      video.state = "Uploading" 
      $http.get("/uploadVid?file=" + filen + "&title=" + title).then(function(resp) { 
       if (resp.data == "0002") { 
        alert("You didn't authorize the App yet, please authorize it to be able to use it .") 
       } 
       if (resp.data == "000X") { 
        alert("An error occured, please retry .") 
       } else { 
        $scope.msg = "the video uploaded, here's the link: " + resp.data 
        video.state = "Done" 
        video.link = resp.data 

        // Do the next video now we've finished this one 
        if (++index < videos.length) { 
         next(); 
        } 
       } 
      }) 
     }) 
    } 
} 

注:寫好了,也許不會有所有我的交叉和T的點綴,但據推測基本面明確。