如何正确使用node.js中的asynchronous函数的承诺?

我在节点中有一个读取文本文件的asynchronous函数,把整个东西放到一个string中,将string拆分成每一行,把它们放到一个数组中,随机返回一个。 在这里我已经实现了一个新的Promise函数来处理它:

exports.readTextFileAndReturnRandomLine = function readTextFile(file) { //reads text file as string, splits on new line and inserts into array, returns random array element return new Promise((resolve, reject) => { var fs = require('fs'); var textFile = fs.readFile(file, 'utf8', (err, data) => { if (err) { return reject(err); } else { var array = data.toString().split("\n"); var response = array[Math.floor(Math.random() * array.length)]; return resolve(response); } }); }); } 

以下是该函数正在读取的文本文件:

 Hello there, Howdy, I will remember your name, Thanks for telling me, Hi Noted, Thanks Well hello there Nice to meet you The pleasure is all mine, Nice name, 

现在在我的根节点(app.js)中,我调用如下所示的函数:

 intents.matches('RememberName', [ function (session, args, next) { var nameEntity = builder.EntityRecognizer.findEntity(args.entities, 'name'); if (!nameEntity) { builder.Prompts.text(session, "Sorry, didn't catch your name. What is it?"); } else { next({ response: nameEntity.entity }); } }, function (session, results) { if (results.response) { fileReader.readTextFileAndReturnRandomLine('./text/remembername.txt').then(function(value) { console.log(value + ", " + results.response); }).catch(function(reason) { console.log(reason); }); } else { session.send("Ok"); } } ]); 

问题是valuenamevariables没有被打印到控制台的顺序,我把他们在这里是我的实际输出:

 my name is chris , Chrisfor telling me, my name is Chris , Chris my name is Chris , Chris my name is Chris , Chrishere, my name is Chris , Chrisfor telling me, my name is Chris , Chrisasure is all mine, my name is Chris , Chris my name is Chris , Chris my name is Chris , Chrisllo there 

这是我的预期输出:

 my name is Chris Hello there, Chris my name is Chris Howdy, Chris my name is Chris Nice to meet you Chris my name is Chris Nice name, Chris 

我相信这与它的同步性有关,但是我不能为了我的生活弄清楚它是什么。

从文本文件中发现字符返回'\r'被带入到string中。 将.trim()方法应用于response解决问题。

好的。 所以你的代码有一点点错误。 承诺的定义需要2个function – resolvereject

但是,当你呼吁承诺,你做一个then()catch() 。 你在then()传递resolve() ,在catch()传递reject() catch()

所以你所要做的就是把最后一段代码改成这样:

 var name = "Chris"; fileReader.readTextFileAndReturnRandomLine('./text/remembername.txt').then(function(value){ console.log(value + ", " + name); }).catch(function(reason) { console.log(reason); }); 

我认为这将工作。