【问题标题】:node.js then() not workingnode.js then() 不工作
【发布时间】:2018-12-23 01:40:07
【问题描述】:

我是 node.js 的新手,所以我试图理解 Promise 并等待 node.js。我想打印文件note.txt。

这是我的代码

    var fs = require('fs');

    fs.readFile('note.txt','utf8').then(contents => console.log(contents))
    .catch(err => console.error(err));

当我运行上面的代码时。我收到以下错误。

fs.readFile('note.txt','utf8').then(contents => console.log(contents))

    TypeError: Cannot read property 'then' of undefined
        at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
        at Module._compile (module.js:635:30)
        at Object.Module._extensions..js (module.js:646:10)
        at Module.load (module.js:554:32)
        at tryModuleLoad (module.js:497:12)
        at Function.Module._load (module.js:489:3)
        at Function.Module.runMain (module.js:676:10)
        at startup (bootstrap_node.js:187:16)
        at bootstrap_node.js:608:3

我为同样的事情尝试了另一种方法。

var fs = require('fs');

async function  read_file(){
  var file_data = await  fs.readFile('note.txt','utf8');
    return file_data;

}
console.log(read_file());

我得到以下错误

Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

当我使用 --harmony 运行时,我得到了同样的错误。我不确定我的代码是否有错误或有什么问题。请帮我理解。

我的环境 节点版本:v8.9.0

node -p process.versions.v8: 6.1.534.46

【问题讨论】:

标签: node.js ecmascript-6


【解决方案1】:

您收到错误是因为fs.readfile 没有返回承诺;因此then 不存在。要将函数用作 Promise,您需要将其包装为 Promise;你可以使用bluebirdQ 之类的东西。

【讨论】:

  • 有没有办法检查函数是否返回一个promise?
  • @KrishnaKarki 最可靠的方法是阅读文档。这就是为什么 javascript 库通常有很好的文档记录(通常有非常精美的网站),而 Java 之类的语言可以从语法本身中发现这一点(因此您的 IDE 可以建议智能感知),其中库文档通常就是 Javadoc 生成的内容
【解决方案2】:

感谢您的回答。我了解到函数必须返回 promise 才能使用 then() 和 catch()。所以代码应该是这样的

var fs = require('fs');

  function  read_file(){
    return new Promise(function(resolve, reject) {
         fs.readFile('note.txt','utf8',function(err,file){
            if(err){
                return reject(err);
            }else{
                resolve(file);
            }
        });
    });


}

read_file().then(
    (data)=>{
        console.log('success: '+data);
    }
).catch((err)=>{
    console.log('error: ',err);
});

【讨论】:

    【解决方案3】:

    如果你使用NodeJs v10,试试fs.promises

    var fs = require('fs').promises; // v10.0 use require('fs/promises')
    
    fs.readFile('note.txt','utf8').then(contents => console.log(contents))
    .catch(err => console.error(err));
    

    如果没有,请使用readFileSync:

    // This code can use for node v10 or lowwer
    var fs = require('fs');
    
    var data = fs.readFileSync('a.json');
    console.log(data);
    

    【讨论】:

      【解决方案4】:

      尝试使用异步等待

      function (async  err => {
          if (err) {
             console.err ....}
      
          await .... <other function included or comes after then .>
          await ... <other function included>
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 1970-01-01
        • 2021-04-18
        • 2020-12-01
        • 1970-01-01
        相关资源
        最近更新 更多