【问题标题】:corodva file read executing both success and failure callbacks科尔多瓦文件读取执行成功和失败回调
【发布时间】:2016-06-03 22:11:34
【问题描述】:

我有一个用 Cordova 编写的移动应用程序。它将一些数据保存到本地存储中,并在下次启动时尝试读取它。

我从这里得到了代码:

https://www.neontribe.co.uk/cordova-file-plugin-examples/

function readFromFile(fileName, cb, cbErr) {
    var pathToFile = cordova.file.dataDirectory + fileName;
    window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();

            reader.onloadend = function (e) {
                cb(JSON.parse(this.result));
            };

            reader.readAsText(file);
        }, cbErr("oops"));
    }, cbErr("darn"));
}

var cbError = function(){}

var fileData;
readFromFile('somefile.txt', function (data) {
    fileData = data;
},cbError );

这一切都在我的 onDeviceReady 函数中。

问题是,当 somefile.txt 存在时,成功回调 (cb) 和错误回调 (cbError) 都会被执行。首先 cbError 然后 cb AND cb 返回我期望的数据。

两个回调都是从 fileEntry.file() 触发的

有人猜到发生了什么吗?

【问题讨论】:

    标签: javascript cordova


    【解决方案1】:

    您的编码方式实际上是调用函数cbErr,而不是将其作为参数传递。看看

    window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
    
            reader.onloadend = function (e) {
                cb(JSON.parse(this.result));
            };
    
            reader.readAsText(file);
        }, cbErr("oops")); // <- This is going to be invoked
    }, cbErr("darn"));  // <- This is going to be invoked
    

    你想做的是这个

    window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
    
            reader.onloadend = function (e) {
                cb(JSON.parse(this.result));
            };
    
            reader.readAsText(file);
        }, function() { // <- This is going to be sent as an argument
            cbErr("oops")
        });
    }, function() { // <- This is going to be sent as an argument
        cbErr("darn")
    });
    

    在您发布的链接中,该人正在使用函数.bind。这是一个非常有趣的函数,当您想要调用一个函数并返回另一个函数时使用它,该函数加载了所提供的范围和参数。看mozilla documentation about it。 如果您想遵循该示例,则应将代码替换为以下内容:

    window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
    
            reader.onloadend = function (e) {
                cb(JSON.parse(this.result));
            };
    
            reader.readAsText(file);
        }, cbErr.bind(null, "oops")); // <- Here is the .bind function
    }, cbErr.bind(null, "darn")); // <- Here is the .bind function
    

    【讨论】:

    • 谢谢。我试过了,它奏效了。但我不明白为什么调用回调是不正确的事情?我想,把函数放在一个变量中,把它传递到适当的地方。我错过了什么?
    • 我很高兴能帮上忙 :) 正如我所说,您正在调用该函数并且返回值被用作未定义的回调。当你第一次开始处理回调时,它有点复杂,但最后它只是将一个函数作为参数发送给另一个函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多