我在 Node 中有一个异步函数,它读取一个文本文件,将整个文件放入一个字符串中,在每个新行处分割字符串,将它们放入一个数组中并随机返回一个。这里我实现了一个新的 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,
现在在我的根 Node (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");
}
}
]);
问题是 value
和 name
变量没有按照我输入的顺序打印到控制台。这是我的 实际输出:
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'
被从文本文件带入字符串中。将 .trim()
方法应用于 response
解决了问题。
关于node.js - 如何在 Node.js 中的异步函数上正确使用 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40361221/