Corodva 文件读取执行成功和失败回调

corodva file read executing both success and failure callbacks

本文关键字:失败 回调 成功 执行 文件 读取 Corodva      更新时间:2023-09-26

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

我从这里得到了代码:

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 );

它都在我的设备就绪函数中。

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

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

有人猜测发生了什么吗?

你编码的方式实际上是在调用函数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 文档。如果要遵循该示例,则应将代码替换为以下内容:

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