【问题标题】:Simple readFile() function in HTML5 / CordovaHTML5 / Cordova 中的简单 readFile() 函数
【发布时间】:2014-09-09 10:02:30
【问题描述】:

这是一个简单的函数,它应该返回当前目录中给定文件的内容。 它正确读取文件内容,但是当我想返回它时,它没有这样做。读取数据时调用reader.onloadend。如何让它从该函数返回数据?

readFile: function(fileName) {
        app.fs.data = "{}"; // clear whatever was stored before
        var hasFile = function(fileEntry) {
            var gotFile = function(file) {
                var reader = new FileReader();
                reader.onloadend = function(evt) {
                    app.fs.data = evt.target.result;
                    console.log("Read as Text: " + file.name);
                    console.log("Data: " + app.fs.data); // app.fs.data contains correct data
                };
                reader.onerror = function(e) {
                    console.log("Error: " + e);
                };
                reader.readAsText(file);
            };
            fileEntry.file(gotFile, app.fs.fail);
        };
        app.fs.dir.getFile(fileName, null, hasFile, app.fs.fail);
        console.log("Actual data: " + app.fs.data); // app.fs.data contains INCORRECT data "{}"
        return app.fs.data;
    }

控制台输出:

Actual data: {}:92
Read as Text: article.json:81
Data: {"id":1405518906105,"name":"My Name","category":0,"abstract":"","content":"","published":false,"lastPublish":null}:82

【问题讨论】:

    标签: javascript html cordova closures html5-filesystem


    【解决方案1】:

    app.fs.data 在您返回时是 {}。 gotfile 是一个异步函数,您返回值的最后两行 readFile 可能在 gotFile 函数之前执行。这是在您的控制台中发生的事情。 我建议你先阅读一下javascript中的回调和闭包。

    【讨论】:

      【解决方案2】:

      终于明白了,我的代码没有意义。我最终使用了 JavaScript Promises,这是一种优雅地处理基于异步函数的方法。更多内容请阅读:http://www.html5rocks.com/en/tutorials/es6/promises/

      由于 Cordova 不支持 Promises,比如 Chrome 或其他浏览器,我使用了这个库,它具有急需的功能:https://github.com/tildeio/rsvp.js

      还有许多其他库实现了 Promises 和其他异步助手,只需使用 google。

      【讨论】:

        猜你喜欢
        • 2012-09-21
        • 2012-10-14
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 2019-02-04
        • 2021-04-11
        • 2014-08-14
        相关资源
        最近更新 更多