1

I need to make a function to load a text file, in a Windows Universal JavaScript app, that returns a string not a "promise".

This code will return a "promise" not a string, so is there a way to embed this in a function (that will wait and then return a string), or a complete other way to go about loading a file.

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){
    ...
});

I need a function that will receive a fileName and return a String;

Lupus Ossorum
  • 450
  • 3
  • 16
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mike Cluck Apr 29 '16 at 23:15

1 Answers1

2

As it was mentioned in a comment, as you deal with asynchronous calls and in particular with promises you should change your architecture: in particular your internal function should return a promise instead of value.

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){
    ...
});

In practice it is also you responsibility to manage possible error states, especially when dealing with file system.

getFileContentAsync(filename).then(function processContent(fileContent){
    ...
}, function processError(error){
    ...
});
Konstantin
  • 884
  • 6
  • 12
  • Why should it return a "promise" instead of a "value", you gave no explanation. What I really want is a string, so why would I have it return a "promise" if that causes repetitive code every time it's called. – Lupus Ossorum May 02 '16 at 17:58
  • 1. You are already dealing with promises as soon, as you use ***Async functions. Functions you are calling (e.g. readTextAsync) return promises, not values. 2. The value simply does not exist at the moment you are calling function, that is why you have to use promises with callback functions. – Konstantin May 02 '16 at 18:55
  • Is there a way to load a file, that does not use promises? – Lupus Ossorum May 30 '16 at 21:53