i can't get the content of a json-file

Hi

I have load an example-app and try some stuff.

In a json-file are stored two elements. -> [{“name”:“Hello”},{“name”:“World”}]

The text of it can i see in the screen of the example-app. But the concatinated strings str, str1, str2, str3, str4 and str5 are without content. In the file bla.txt is only “012345”.

Any hint, what’s wrong in my code?

Hey Daniel when you post make sure to paste actual formatted code that we can copy paste instead of an image of the code.

Regarding your question take a look at: https://www.fusetools.com/community/forums/howto_discussions/load_local_json_in_new_version

Hi Edwin

Here the code:

var Observable = require('FuseJS/Observable');
var Storage = require("FuseJS/Storage");


var test = Observable();
var str = "";
var str1 = "";
var str2 = "";
var str3 = "";
var str4 = "";
var str5 = "";

read();
save();

function read () {
    Storage.read("test.json").then(function(content) {
        str = str + content + ":"; // test
        data = JSON.parse(content);
        data.forEach(function(e) {
            str1 = str1 + e; //test
        });
        for (var i = 0; i < data.length; i++) {
            str2 = str2 + data[i].name; //test
            test.add(data[i]); // content for ux
        };
        test.forEach(function(e) {
            str3 = str3 + e.name; //test
        });
    }, function(error) {});
}

function save() {
    test.forEach(function(f) {
        str5 = str5 + f.name; //test
    });
    Storage.write("bla.txt", "0" + str + "1" + str1 + "2" + str2 + "3" + str3 + "4" + str4 + "5" + str5);
}

items = Observable();
function addItem(){
items.add({
    color : [Math.random(), Math.random(), Math.random(), 1],
    height : (Math.random() + 1.0) * 80
    });
}

module.exports = {
    test: test,
    items : items,
    addItem : addItem
};

my problem is, that i see the contents of the json-file in the previewwindow, but not in the strings str, str1, str2,…

Hi Daniel, Since read() is async it might not have finished and returned content before you call save().

In other words, your call to save() executes before the code that fills up test.

If you instead call save() from inside the promise (after the test.forEach) then everything should behave as you expect.

Hi Remi

Many thanks. That was the problem. Now it works fine.