【问题标题】:Something Wrong With My Asynchronous JavaScript Code我的异步 JavaScript 代码出了点问题
【发布时间】:2021-01-02 23:58:48
【问题描述】:
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;
        }
    }
}

我试图检查目录中是否存在文件,使用 fs 的承诺,有问题的部分总是返回 true。我没有想法。

【问题讨论】:

  • 您是否尝试过调试您的代码并逐行调试?

标签: javascript asynchronous fs


【解决方案1】:

你调用if (this.fileExists...),它等价于if (true),因为this.fileExists总是返回一个Promise,它会被隐式强制转换为true的布尔值

所以你应该用await 来调用fileExists,并将这个调用包装在一个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
    }
  }
}

【讨论】:

  • @hgb123 为什么需要将此调用包装在 IIFE 函数中?
  • @Sohan 因为this.fileExists 是用await 调用的,而AFIK,我们无法创建构造函数async..
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
相关资源
最近更新 更多