Monday, 24 April 2017

Promise inside a for loop [duplicate]

This question already has an answer here:

I have a function returning a promise after it lists files from a directory:

export const listFiles = dir => (
    new Promise((resolve, reject) => {
        const files = [];
        glob(`${dir}/**/*`, {}, (err, filenames) => {
            filenames.forEach(filename => {
                if (isFile(filename)) files.push(filename);
            });
            resolve(files);
        });
    })
);

Now I want to create a function that takes multiple directories, and returns value when all files from them are read:

export const listMultipleFiles = dirs => (
    new Promise((resolve, reject) => {
        let allFiles = [];
        dirs.forEach((dir, i) => (
            listFiles(dir)
            .then(files => {
                allFiles = allFiles.concat(files);
                if (i === dirs.length - 1) {
                    resolve(allFiles);
                }
            })
            .catch(err => reject(err))
        ));
    })
);

It of course won't work, as forLoop index will finish before any promise. Is there a way to solve this?



via user99999

No comments:

Post a Comment