2016-06-20 75 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的点缀,但据推测基本面明确。