In nodejs, stats is used to judge whether the file is a folder, and the resolve () statement of promise is placed in the block of judgment statement, which leads to the error of the program.

recently in learning the koa framework to build a node environment, writing a small case requires the following: the node program reads a path, and if it is a folder, put the folder name into the list collection. Promise is used in the program to do asynchronous processing. The code is as follows.

const getPath = (fileName) => {
    return new Promise((resolve, reject) => {
        fs.stat(basePath + fileName, (err, stats) => {
            if (err) {
                console.log("");
                reject("");
                return;
            }
            if (stats.isDirectory()) {
                newFiles.push(fileName);
                console.info(fileName + " ----------- " + stats.isDirectory());
                resolve();
            }
        })
    })
}

problem description:

;

try the solution code:

const getPath = (fileName) => {
    return new Promise((resolve, reject) => {
        fs.stat(basePath + fileName, (err, stats) => {
            if (err) {
                console.log("");
                reject("");
                return;
            }
            if (stats.isDirectory()) {
                newFiles.push(fileName);
                console.info(fileName + " ----------- " + stats.isDirectory());
            }
            resolve();
        })
    })
}

so that the program can execute normally. But I don"t understand the reason. Please give me some guidance.

Feb.28,2021
As written in

, as long as stats.isDirectory () returns false, which means it is not a folder, there will be an exception in your promise without resolve,.

Menu