T
T
Tipylja2018-08-25 19:08:00
recursion
Tipylja, 2018-08-25 19:08:00

How to get array of values ​​from async recursive function?

There is a function, recursive, that runs through the file system

const scanDir = async (dir, filelist = []) =>{
    const files = await readdir(dir);
    files.forEach(async (file)=>{
        const dirFile = path.join(dir, file);
        try {
            filelist = await scanDir(dirFile, filelist);
        }
        catch (err) {
            if (err.code === 'ENOTDIR' || err.code === 'EBUSY')
            {                
                filelist = await [...filelist, dirFile];
                
            }
            else throw err;
        }
    });

    return filelist;
};

Connected modules and features

const fs = require('fs')
    ,{promisify} = require('util')  
    ,readdir = promisify(fs.readdir)
    ,exists = promisify(fs.exists)
    ,mkdir = promisify(fs.mkdir)
    ,copyFile = promisify(fs.copyFile);


I probably don’t understand something, there is little experience, but as I see it, it returns the filelist array, which is passed to the recursion further.
But how to accept this array after the end of the function?
That is, it doesn’t work like this:
const myArr = scanDir(dir);
I tried to wrap it in an async function and wait until scanDir resolves, something like this:
(async()=>{
const myArr = await scanDir(dir);
})()


But that doesn't work either. I also try this:

scanDir(dir).catch(
    (err)=>{
        console.log(err);
    }
).then(

    (data)=>{console.log(data.length)}

);


An array is returned in data, but it is empty. Can you please tell me how to get the full array from the scanDir function?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-08-27
@EShein

Promise.all([array of promises]).then( (data ) => {})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question