1

I want to retrieve a list of all my MP3 files and return the list only when searching is complete, I use this code but it does not work as I expect:

(it runs on NativeScript)

const fs = require("tns-core-modules/file-system");
const root = android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString();
let retrievedData = [];

export async function fileRetriever( mode , path=root ) {

    retrievedData = [];

    console.log('start');
    if ( mode == 'songs' ) retrievedData = await songSeeker();
    console.log('should be received');
    console.log(retrievedData);
    console.log('stop');

    return retrievedData;

}

function songSeeker ( path = root ) {

    let documents = fs.Folder.fromPath( path );

    documents.getEntities()
    .then( ( entities ) => {
        entities.forEach( ( entity ) => {

            // ------ catch on Folder
            if ( fs.Folder.exists( entity.path ) ) {
                songSeeker ( entity.path );

            // ------ catch on File
            } else if ( entity.extension == '.mp3' )  {
                let tmpData = { 
                    title: entity.name , 
                    path: entity.path 
                };
                retrievedData.push( tmpData );
            }

        } );

    } ).catch( ( err ) => {
        console.log(err.stack);
    } );

    return retrievedData;
}

I expect to get the complete list, but it returns just the first file!

the result is:

JS: 'start'
JS: 'should be received'
JS: [ { title: 'Hatef music.mp3',
JS:     path: '/storage/emulated/0/Hatef music.mp3' },
JS:   [length]: 1 ]
JS: 'stop'
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mbojko Oct 17 '19 at 06:49
  • "*I use this code but it does not work as I expect*" what is the problem with it? What happens and what do you expect to happen? Where (roughly) does it fail? – VLAZ Oct 17 '19 at 06:54
  • I updated the post, and provide more info –  Oct 17 '19 at 07:04
  • 1
    I recommend rewriting your code in TypeScript instead of JavaScript because your `songSeeker` function doesn't seem to return a `Promise` yet the caller is using `await` with it - TypeScript will reveal mistakes like that. – Dai Oct 17 '19 at 13:13
  • 1
    Also, when using chaining with collections, you shouldn't mutate shared state (i.e. don't do `retrievedData.push( tmpData )`, instead use techniques like `filter`, `map`, and so on. – Dai Oct 17 '19 at 13:14
  • Dear @Dai may I ask you to provide a link that I can learn more about your last comment? (I have no cue what is wrong with `push` method here.) –  Oct 17 '19 at 14:01
  • @hatef There isn’t a single link or web-page I can give, sorry - these are the kinds of things taught in a computer-science degree or functional-programming course. – Dai Oct 17 '19 at 14:04

0 Answers0