T
T
timonck2019-12-16 16:35:43
JavaScript
timonck, 2019-12-16 16:35:43

How to rewrite a function with promises?

Good afternoon,
I need to recursively find a file by extension, for this I have

const fs = require('fs');
const path = require('path');

let pathSupplied = './';
let extFilter = 'js';

let extension = (element) => {
    let extName = path.extname(element);
    return extName === '.' + extFilter;
};

let walk = function (dir) {
    fs.readdir(dir, function (err, list) {
        list.forEach((item) => {
            let itemPath = path.join(dir, item);
            fs.stat(itemPath, (e, stats) => {
                if (stats.isDirectory()) {
                    walk(itemPath);
                } else {
                    if(extension(itemPath)){
                        console.log(itemPath)

                    }
                }
            });
        });
    })
}
walk(pathSupplied)

I need to write the result of its search into an array, for this I need to use Promise
, I can’t figure out how to rewrite this through Promise?
Please tell me how to solve this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
EVG, 2019-12-16
@f_ban

const fs = require('fs');
const path = require('path');

let pathSupplied = './';
let extFilter = 'js';

let extension = (element) => {
    let extName = path.extname(element);
    return extName === '.' + extFilter;
};

let walk = function (dir) {
    const result = [];

    fs.readdir(dir, function (err, list) {
        list.forEach((item) => {
            let itemPath = path.join(dir, item);
            fs.stat(itemPath, (e, stats) => {
                if (stats.isDirectory()) {
                    walk(itemPath);
                } else {
                    if(extension(itemPath)){
                        console.log(itemPath)
                        result.push(itemPath);
                    }
                }
            });
        });
    });

    return result;
}

walk(pathSupplied);

walkAsync = (dir)=>{
    return new Promise((resolve)=>{
        resolve(walk(dir))
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question