【问题标题】:TypeError: "FunctionName" is not a function during async and awaitTypeError:“FunctionName”在异步和等待期间不是函数
【发布时间】:2018-07-15 19:19:25
【问题描述】:

我是 javascript 新手,并试图了解 Async 和 Await。 这是我编写的代码,它尝试从文件中读取,如果找不到文件,它会拒绝。

async function getFileAsString(path) {
    if (!path) {
        throw "you need to give a path!"
    }

    const fileContent = await fileCheck(path);
    console.log(fileContent)
}

var fileCheck = function(path) {
    return new Promise(function(resolve, reject) {
        if (fs.readFileAsync(path, "utf-8")) {
            resolve("File found!")
        } else {
            reject("File not found!!")
        }
    })
}

我收到一条错误消息,提示“TypeError:fileCheck 在异步和等待期间不是函数。我无法找出原因。有人可以帮我解决这个问题吗? 谢谢。

【问题讨论】:

  • fileCheck 的使用方式...
  • 函数赋值声明没有提升到作用域的顶部,因此是未定义的。
  • fileCheck 用于检查路径是否存在。如果它解决了,否则它会拒绝
  • var fileCheck = function 应该是async function fileCheck 吧?
  • 首先:没有readFileAsync,看看docs。为什么你认为可以将异步代码放在 if 语句中并获得有意义的结果? Promise 是一个对象 abd 因此总是真实的,您的 fileCheck 将在文件实际检查之前很久就解决。

标签: javascript asynchronous async-await


【解决方案1】:

你的代码有几个问题:

1)

 fs.readFileAsync(path, "utf-8")

不存在。只需省略AsyncreadFile 默认是异步的。

2)

 if(fs.readFile(path, "utf-8"))

如上所述,readFile 是异步的,这意味着它不返回任何内容 (= undefined),而是在某个时候调用传递的回调。所以你要么使用同步版本:

 try {
   fs.readFileSync(path, "utf-8")
   // ... All fine
 } catch(error){
   // File corrupted / not existing
 }

或者你签入回调:

 fs.readFile(path, "utf-8", function callback(error, data){
   if(error) /*...*/;
 });

3) 使用函数表达式:

var checkFile = function(){}

是个坏主意,因为它引入了提升问题等等。


 function checkFile(path){
   return new Promise((res, rej) => {
      fs.readFile(path, "utf-8", function callback(err, data){
         err ? rej(err) : res(data);
      });
   });
}

【讨论】:

  • 可能不应该缩写resolve() / reject(),否则+1
【解决方案2】:

只需使用util.promisify() 包装回调式异步函数fs.readFile()

var readFile = util.promisify(fs.readFile);

async function getFileAsString(path) {
    // `readFile()` will throw proper error if `path` is invalid
    const fileContent = await readFile(path, 'utf-8')
    console.log(fileContent)
    return fileContent
}

【讨论】:

    【解决方案3】:

    前几天我正在这样做,上面有几件事出错了。试试这样的:

    const fs = require('fs');
    
    class FileManager {
      async getFileAsString(path) {
        if (!path) {
            throw "you need to give a path!"
        }
    
        const fileContent = await this.fileCheck(path);
        console.log(fileContent)
      }
    
      fileCheck(path) {
        return new Promise(function(resolve, reject) {
          fs.readFile(path,'utf8',(err, result) => {
            if (err) reject(err);
            else resolve(result);
          });
        })
      }
    }
    
    // Example usage
    const fileManager = new FileManager();
    fileManager.getFileAsString('./release.js');
    

    这是一些额外的代码,但是把它放在一个类中可以防止上面提到的提升问题。上周我还注意到,当我这样做时,async / await 在不与类一起使用时表现得很奇怪,不知道那是怎么回事......

    [编辑]

    还有一个 readFileSync 方法已经这样做了,看看这个线程:

    Difference between readFile and readFileSync

    【讨论】:

    • 我们不定义fileCheck吗?
    • 1) async / await 在类之外使用时不会表现异常 2) 这段代码仍然无法正常工作,其中有太多错误
    • @JonasW。比如?
    • @Asleepace 也许你应该在发布之前测试你的解决方案,然后你就会知道......
    • @asleepace 实际上不是我们的工作来解决您的问题。
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2019-11-28
    • 2019-06-16
    • 2018-02-03
    • 1970-01-01
    • 2022-07-06
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多