简体   繁体   English

Typescript async等待不使用FS

[英]Typescript async await not working with the FS

typescript async await doesn't work with the current senario dealing with the NODE js FS. typescript async await不适用于处理NODE js FS的当前senario。

Following the code. 遵循代码。

   public static FileExists(filePath: string): Promise<boolean> {
        return new Promise<boolean>(async (resol, reje) => {
            try {
                fs.accessSync(filePath, fs.F_OK);
                resol(true);
            }
            catch (e) {
                resol(false);
            }
        });
    }

     public static async CreateDirectory(name: string): Promise<boolean> {
    return new Promise<boolean>(async (resolve, reject) => {
        let dirExist: boolean = await FileManager.FileExists(name);
        try {
            if (!dirExist) {
                fs.mkdirSync(name);
            }
            resolve(true);
        } catch (e) {
            resolve(false);
        }

    });

  for (var i = 0; i < paths.length; i++) {
                var element = paths[i];
                fullPath += element + "/";
                let a = await FileManager.CreateDirectory(fullPath);
                console.log(fullPath);
            }

I have added the await in the foreach but the loop continues and I don't get value of a before the loop iteration , instead it gives all the values at the end. 我在foreach中添加了await但是循环继续,我在循环迭代之前没有得到a的值,而是在结尾处给出了所有值。

Note: i can add the promise to all object that are present in the loop but the problem is that it calls every time either the file is present or not, if the file isn't present it tries to create the same directory multiple times or each of the time file exist is called. 注意:我可以将承诺添加到循环中存在的所有对象,但问题是每当文件存在与否时它都会调用,如果文件不存在则尝试多次创建相同的目录或者每个时间文件都存在。

What i want that it should check for file once and not found , it should create directory and afterward the directory existence would be true so it woill stop creating same directory multiple muyltiple times. 我想要它应该检查文件一次但没有找到,它应该创建目录,然后目录存在将是真的所以它woill停止创建相同的目录多个muyltiple次。

You need to properly promisify an asynchronous file system method, so you cannot use accessSync and mkdirSync (or you could use them, but then promises and async function would be pointless). 您需要正确地宣传 异步文件系统方法,因此您不能使用accessSyncmkdirSync (或者您可以使用它们,但是承诺和async函数将毫无意义)。

Instead, do 相反,做

public static fileExists(filePath: string): Promise<boolean> {
    return new Promise<boolean>(async resolve => {
        fs.accessSync(filePath, fs.F_OK, err => {
            if (err) resolve(false);
            else resolve(true);
        });
    });
}

public static async createDirectory(name: string): Promise<boolean> {
    if (!await this.fileExists(name)) {
        await new Promise(async (resolve, reject) => {
            fs.mkdir(name, err => {
                if (err) reject(err);
                else resolve();
            });
        });
    }
    return true;
}

var fullPath = ""
for (var element of paths)
    fullPath += element + "/";
    let a = await FileManager.createDirectory(fullPath);
    console.log(fullPath);
}

However, notice that using fs.access to check before an action is not recommended . 但是,请注意, 建议不要在执行操作前使用fs.access进行检查 You should instead simply catch the error: 您应该只是捕获错误:

public static createDirectory(name: string): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
        fs.mkdir(name, err => {
            if (err) reject(err);
            else resolve();
        });
    }).then(() => true, err => {
        if (err.code == "EEXIST") return false;
        else throw err;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM