Returning a value from Cordova File Plugin when called from a function

空扰寡人 提交于 2021-01-29 15:09:38

问题


I have seen someone has posted a similar question but it doesn't really fit what I'am looking for:

Here is my code:

$(document).ready(function(){
  $("#btnTest").bind("click", function(){
    a = createFile();
      alert(">> "+a); // Displayed returned value;
  });

  function createFile(){
    var type = window.TEMPORARY;
    var size = 5*1024*1024;
    window.requestFileSystem(type, size, successCallback, errorCallback)

    function successCallback(fs) {
      fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
        alert('File creation successfull!');
        return 1; // Return value;
      }, errorCallback);
    }

    function errorCallback(error) {
      alert("ERROR: " + error.code)
      return 2; // Return value;
    }
    }   
});

Basically once the createFile() function is called it will return either 1 (success) or 2 (error). Problem is I do not know how I can return the value and call it properly?

Any help would be really good.


回答1:


I would create a global variable in your function called returnValue and set its value

$(document).ready(function(){
  $("#btnTest").bind("click", function(){
    a = createFile();
      alert(">> "+a); // Displayed returned value;
  });

  function createFile(){
    var returnValue;
    var type = window.TEMPORARY;
    var size = 5*1024*1024;
    window.requestFileSystem(type, size, successCallback, errorCallback)

    function successCallback(fs) {
      fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
        alert('File creation successfull!');
        returnValue = 1; // Return value;
      }, errorCallback);
    }

    function errorCallback(error) {
      alert("ERROR: " + error.code)
      returnValue = 2; // Return value;
    }
    return returnValue;
  }
    
});


来源:https://stackoverflow.com/questions/65766037/returning-a-value-from-cordova-file-plugin-when-called-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!