Good afternoon everyone, I have already asked a similar question two or three weeks back here, but I could not solve the problem in that way. This problem looks like this: using the phonegap - getMetadata() function phonegap - getMetadata() I get the data from the function. The code looks like this:

 entry.getMetadata(lastFileModDate, fail); //lastFileModDate функция которая выводит дату 

The getMetadata method gets the name of the function " lastFileModDate ", then creates the " metadata " object and calls the lastFileModDate function, passing this object. This function looks like this:

 function lastFileModDate(metadata) { console.log(metadata.modificationTime); } 

A simple assignment of a variable gives nothing undefined so I appeal to you, people. I tried many different methods, none of them came up.

Here is the function in which everything is going on:

 function listResults(entries) { entries.forEach(function (entry) { //.... var a; function lastFileModDate(metadata) { console.log(metadata.modificationTime); a = metadata.modificationTime; } entry.getMetadata(lastFileModDate, fail); //Отправка функции lastFileModDate console.log(a); //undefined } 

How do I get the data that comes in lastFileModDate (metadata)?

 //проверяем готов ли девайс к использованию document.addEventListener("deviceready", onDeviceReady, false); //та же проверка function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail); } //массив списка файлов function toArray(list) { return || [], 0); } //смотрим всем папки function onFileSystemSuccess(fileSystem) { var dirReader = fileSystem.root.createReader(); var entries = []; var readEntries = function () { dirReader.readEntries(function (results) { if (results.length) { entries = entries.concat(toArray(results)); listResults(entries); } }, fail); }; readEntries(); } //какую папку открывать function onFileSystemSuccess(fileSystem) { fileSystem.root.getDirectory(fileListDir, { //адрес к папке create: true, exclusive: false }, getDirSuccess, fail); } //если папка существует то открываем и входим в неё function getDirSuccess(dirEntry) { var directoryReader = dirEntry.createReader(); directoryReader.readEntries(listResults, fail); } var gStr = ''; //посылаем список файлов и папок и сами файлы function listResults(entries) { entries.forEach(function (entry) { if (entry.isDirectory) { gStr += 'dir_' + dir_i + '=' + + " "; dir_i++; } else { //последняя дата редактирования файла function lastFileModDate(metadata) { //console.log(metadata.modificationTime); modTime = metadata.modificationTime; } //размер файла function fileSize(file) { //console.log(file.size); fSize = file.size; } entry.getMetadata(lastFileModDate, fail); console.log(modTime); entry.file(fileSize, fail); gStr += 'file_' + file_i + '=' + + ' date_file_' + file_i + '=' + +' file_size_' + file_i + '=' + fSize + " | "; file_i++; } }); //если файл тогда -> if (itm.locname.isFile) { //КИДАЕМ ФАЙЛЫ } else { //посылаем нас сервер сами файлы /*$.post(task_url + "/" + userfotos, gStr, function(data) { //alert("Data Loaded: " + data); } );*/ //console.log(gStr); console.log(gStr); } } //если не получилось function fail(evt) { console.log("Error " + + evt.error + evt.code); } //если получилось function win(r) { console.log("success"); console.log("Sent = " + r.bytesSent); } 
  • one
    console.log (a); // undefined And what are you trying to do later with the variable "a"? pass its value to another function? - iKuzko
  • one
    entry.getMetadata (metadata.modificationTime, fail); // Sending the lastFileModDate function - Gorets
  • one
    console.log (metadata.modificationTime); - and then something is displayed? - Gorets
  • one
    it turns out you want to assign an array to a variable - Gorets
  • one
    either assign an array and take a 1 or I-th element, or immediately without assigning which element to take, or iterate over it and take the desired element ... - Gorets

2 answers 2

In addition to syntax errors and not declared variables in the above text, the error is that FileEntry . getMetadata () (the same for directories), as well as FileEntry . file () is asynchronous , otherwise why are there callbacks. Finding the file size or modification date immediately after calling these functions is meaningless. Android is not so fast =)

In general, it's so easy to fix the error. It is necessary to rewrite the receipt of the list of files and their parameters in asynchronous style. Metadata, by the way, is not necessary to receive, and the date and size are in the file itself ( File ).

  • And you can more in detail about the "rewrite asynchronously," like this? "Metadata, by the way, is not necessary to receive, and the date and size are in the file itself (File)." Have to rewrite everything? When I write entry.size in my code and entry.lastModifidate gives me undefined, how do I need to rewrite what would output normally? - dajver
  • one
    @Yura Ivanov, great, it’s been waiting for you here for 2-3 weeks and 2 days .. =) good answer .. - Gorets
  • @Gorets, mnogabukf was, I thought, they could cope without me, I avoided it for a long time =) @dajver, if you decide head-on, then you need to create a global array of files, call file () in a loop on entries, and fill this global array with all necessary data. The fact of the completion of filling is the number in the file array = the number in the array of entries. then when everything is filled, it will be possible to run through this global array and get gStr by concatenation. something like this. - Yura Ivanov

Try to replace

  var a; function lastFileModDate(metadata) { console.log(metadata.modificationTime); a = metadata.modificationTime; } entry.getMetadata(lastFileModDate, fail); //Отправка функции lastFileModDate console.log(a); //undefined 


  function lastFileModDate(metadata) { console.log(metadata.modificationTime); return metadata.modificationTime; } var a = entry.getMetadata(lastFileModDate, fail); console.log(a); //undefined 

The meaning is:

  • invoked entry.getMetadata ()
  • upon successful data retrieval, it calls lastFileModDate and transfers data
  • The lastFileModDate of the data gets a metadata.modificationTime and returns it from the function.
  • var a = entry.getMetadata (lastFileModDate, fail); gets this data.

UPD : It is strange that you do not work. Here I wrote the same principle for the test, which you explained and it works fine with assignment.

 var a; //объявляем переменную function getMetadata(callBackFunction) { //наша функция getMetadata var metadata = {}; //получаем объект сданными metadata.modificationTime = '33'; // допустим вот такое время создания callBackFunction(metadata ); // вызываем колбэк и передаем туда данные } function lastFileModDate(metadata) { a = metadata.modificationTime; //присваеваем значение времени в нашу переменную } getMetadata(lastFileModDate); //Вызываем функцию для файла alert(a); //проверяем значение переменной А​ 


Perhaps you need more code to find the error.

Put down console.log () after each action and look at what stage it fails :)

  • one
    You try the first option, the second will not work (I have already looked into the documentation), but the first should work :) The second option is now deleted as irrelevant. - iKuzko
  • one
    Well, do not recreate the whole model for me to test? entry.getMetadata () - here it is a method of the object that makes certain manipulations. In my example, a stand-alone function that does about the same. The principle of appropriation itself would have to work out, but you are not working. And what is the reason for this piece of code is difficult to determine. We don’t see all the program code :) One way out is debuging. - iKuzko
  • one
    And if you try this, what will the logs be? function lastFileModDate (metadata) {console.log (metadata.modificationTime); modTime = metadata.modificationTime; console.log (modTime); } console.log (modTime); - iKuzko
  • one
    Ok, and does fileSize from the function below return the value or undefined too? - iKuzko
  • also undefined - dajver