2016-04-29 47 views
1

我需要創建一個函數來加載Windows通用JavaScript應用程序中的文本文件,該文件返回的字符串不是「承諾」。UWP JavaScript加載本地文本文件,沒有「異步調用」

這段代碼將返回一個「promise」而不是一個字符串,所以有一種方法可以將它嵌入到一個函數中(它將等待並返回一個字符串),或者完成其他加載文件的方式。

function getFileContentAsync(fileName) { 
    var fileName = new Windows.Foundation.Uri("ms-appx:///" + fileName); 
     return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(fileName).then(function (file) { 
    return Windows.Storage.FileIO.readTextAsync(file); 
    }); 
}); 

//usage 
getFileContentAsync(filename).then(function(fileContent){ 
    ... 
}); 

我需要一個函數,它將接收一個fileName並返回一個String;

+0

可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an - 異步調用) –

回答

1

正如在評論中提到的那樣,當你處理異步調用,尤其是承諾時,你應該改變你的架構:特別是你的內部函數應該返回一個承諾而不是價值。

function getFileContentAsync(fileName) { 
    var fileName = new Windows.Foundation.Uri("ms-appx:///" + fileName); 
    return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(fileName).then(function (file) { 
     return Windows.Storage.FileIO.readTextAsync(file); 
    }); 
}); 

//usage 
getFileContentAsync(filename).then(function(fileContent){ 
    ... 
}); 

在實踐中,您也有責任管理可能的錯誤狀態,特別是在處理文件系統時。

getFileContentAsync(filename).then(function processContent(fileContent){ 
    ... 
}, function processError(error){ 
    ... 
}); 
+0

爲什麼它應該返回一個「承諾」而不是「價值」,你沒有給出任何解釋。我真正想要的是一個字符串,那麼爲什麼我會讓它返回一個「承諾」,如果每次調用都會導致重複的代碼。 –

+0

1.當您使用***異步功能時,您已經在儘快處理承諾。您正在調用的函數(例如,readTextAsync)會返回promise,而不是值。 2.當你調用函數時,該值根本不存在,這就是爲什麼你必須使用帶回調函數的promise。 – Konstantin

+0

有沒有加載文件的方法,不使用承諾? –

相關問題