简体   繁体   English

node.js then()无法正常工作

[英]node.js then() not working

I am new to node.js so I am trying to understand promises and wait on node.js. 我是Node.js的新手,所以我试图了解Promise并等待node.js。 I want to print the file note.txt. 我要打印文件note.txt。

Here is my code 这是我的代码

    var fs = require('fs');

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

When I run above code. 当我运行以上代码时。 I get the following error. 我收到以下错误。

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

And I try another method for the same thing. 我尝试用另一种方法处理同一件事。

var fs = require('fs');

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

}
console.log(read_file());

And I get following error 我得到以下错误

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

I get the same error when I run with --harmony. 使用--harmony运行时,出现相同的错误。 I m not sure if there is bug on my code or what is wrong. 我不确定我的代码中是否有错误或出了什么问题。 Please help me understand. 请帮助我理解。

My Environment Node version: v8.9.0 我的环境节点版本:v8.9.0

node -p process.versions.v8: 6.1.534.46 节点-p process.versions.v8:6.1.534.46

You're getting errors because fs.readfile doesn't return a promise; 您会因为fs.readfile不返回诺言而fs.readfile hence then doesn't exist. 因此, then不存在。 For you to use the function as a promise, you will need to wrap it up as a promise; 为了将功能用作承诺,您需要将其包装为承诺。 you could use something like bluebird or Q . 您可以使用诸如bluebirdQ之类的东西。

If you use NodeJs v10, try fs.promises : 如果您使用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));

If not, use readFileSync : 如果没有,请使用readFileSync

// This code can use for node v10 or lowwer
var fs = require('fs');

var data = fs.readFileSync('a.json');
console.log(data);

Thank you for the answers. 谢谢你的回答。 I learned that function must return promise in order to use then() and catch(). 我了解到该函数必须返回promise才能使用then()和catch()。 So the code should be like this 所以代码应该像这样

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);
});

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

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