Home > Net >  NodeJS - Returning 'undefined'
NodeJS - Returning 'undefined'

Time:02-01

I am learning NodeJS (generally I write in PHP). Please help me figure out the Promises. Now the 'getDataFromDir' function returns 'undefined'. I read the documentation, but apparently I don't fully understand something. Thanks in advance!

const host = 'localhost';
const port = 3000;
const __dirname = process.cwd();

async function getDataFromDir(fileName){
    fsp
        .readdir(path.join(fileName))
        .then(async (indir) => {
            const list = []
            for (const item of indir) {
                const src = await fsp.stat(path.join(fileName, item))
                list.push(item)
            }
            return list;
        })
}

const server = http.createServer(async (req, res) => {
    const result = await getDataFromDir(__dirname);
    result
        .then((list) => {
            console.log(list);
    });
});

CodePudding user response:

It seems like your return statement is returning only for the callback function under your .then statement. You should be able to use the await statement with your initial request and achieve a similar result.

async function getDataFromDir(fileName){
    let indir = await fsp.readdir(path.join(fileName));
    const list = [];
    for (const item of indir) {
        const src = await fsp.stat(path.join(fileName, item));
        list.push(item);
    }
    return list;
}

  • Related