2013-08-23 37 views
0

我是Promise和WinJS的新手,目前正在開發一款應用程序。WinJS中的嵌套承諾以及如何等待最終完成

在某些情況下,我需要使用backgroundDownloader下載文件並將其保存在本地文件夾中,然後讀取它並處理數據。

有一個函數啓動這個過程,我想在繼續之前等待整個過程的完成。然而,通過一些調試,我意識到在第一個承諾成功返回之後,程序繼續進行,而不應該(我認爲)。我相信它應該等待所有的承諾,一個接一個地成功。

下面是代碼:

發起過程中的功能:

功能startDownload(){ getData.done(函數(){ 等等等等等等 } }

由上述函數調用的getData函數:

getData: function() { 
     return downloadFtp(staticUrl, filePath) 
      .then(function (response) { 
       var data = openFile(response.resultFile.name); 
       return data; 
      }); 
    } 

的downloadFtp功能,下載並保存內容,並返回一個承諾

downloadFtp: function (uriString, fileName) { 
     var download = null; 
     try { 
      // Asynchronously create the file in the pictures folder. 
      return Windows.Storage.ApplicationData.current.localFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting) 
       .then(function (newFile) { 
        var uri = Windows.Foundation.Uri(uriString); 
        var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader(); 

        // Create a new download operation. 
        download = downloader.createDownload(uri, newFile); 

        // Start the download and persist the promise to be able to cancel the download. 
        return download.startAsync(); 
       }); 
     } catch (err) { 
      displayException(); 
     } 
    }, 

打開本地文件,並返回一個承諾的中openFile功能:

openFile: function (file) { 
     return Windows.Storage.ApplicationData.current.localFolder.getFileAsync(file) 
      .then(function (content) { 
       var content = readFile(content); 
       return content; 
      }); 
    }, 

ReadFile函數讀取的數據文件並將其發送到數據處理器:

readFile: function (content) { 
     return Windows.Storage.FileIO.readTextAsync(content) 
      .done(function (timestamp) { 
       var text = processData(timestamp); 
       return text; 
      }); 
    }, 

在startDownload函數中,我注意到它沒有等待完成進入done()函數之前的整個過程。有沒有簡單的解決方法,或簡單的方法來處理一般的嵌套承諾?

我很感謝這裏的任何幫助。

回答

0

我打算將您的示例轉換爲僞代碼,以便更容易地發現問題。

downloadFtp.then(getFileAsync.then(readTextAsync.done(processData))) 
      .done(BLAH) 

問題是解決downloadFile觸發兩個回調,getFileAsync和BLAH。 getFileAsync回調函數返回一個可能在此狀態下未解析的promise,但回調仍然會立即結束,所以BLAH可以自由運行。稍後,getFileAsync被解析並調用其他回調函數。

您可以做的最好的事情是切換到承諾鏈模型,使控制執行流程更容易。

+0

當我在等待答案時,我將done(processData)中的done關鍵字更改爲「then」,並且所有內容似乎都再次起作用。我看不出如何解決這個問題。 你的回覆也是有道理的。謝謝。我會嘗試更改代碼以反映您的建議。 –