我的异步JavaScript代码有问题

时间:2020-09-16 07:33:35

标签: javascript asynchronous fs

class Main {
    constructor() {
        this.argument = process.argv.splice(2);
        this.fileToCopy = this.argument[0];
        this.destination = this.argument[1] ? this.argument[1] : '';

        this.callAdress = process.cwd();
        this.finalAdress = `${this.callAdress}\\` + this.destination;
       

        //Problematic Part
        if(this.fileExists(this.fileToCopy, this.finalAdress)) console.log("EXISTS")
        else console.log("DOESNT EXISTS");
    }

    async fileExists(file, path) {
        try {
            let files = await fs.readdir(path);
            
            return files.includes(file);
        } catch(e) {
            console.log("ERROR", e)
            return false;
        }
    }
}
我试图检查文件是否存在于directroy中,使用promise for fs,有问题的部分总是返回true。我没有想法。

1 个答案:

答案 0 :(得分:1)

您调用if (this.fileExists...)等效于if (true),因为this.fileExists总是返回一个Promise,它将被隐式强制为true的布尔值

因此,您应该改为使用fileExists来调用await,并将此调用包装在IIFE函数中

并且请记住在IIFE函数的开头放置一个分号,以避免与上一行(this.destination(async...))相混淆

class Main {
  constructor() {
    this.argument = process.argv.splice(2)
    this.fileToCopy = this.argument[0]
    this.destination = this.argument[1] ? this.argument[1] : ''

    this.callAdress = process.cwd()
    this.finalAdress = `${this.callAdress}\\` + this.destination

    ;(async () => {
      if (await this.fileExists(this.fileToCopy, this.finalAdress))
        console.log('EXISTS')
      else console.log('DOESNT EXISTS')
    })()
  }

  async fileExists(file, path) {
    try {
      let files = await fs.readdir(path)

      return files.includes(file)
    } catch (e) {
      console.log('ERROR', e)
      return false
    }
  }
}