I have an asynchronous function in node that reads a text file, puts the whole thing into a string, splits the string at every new line, puts them into an array and returns one at random. Here I have implemented a new Promise function to deal with it:
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);
}
});
});
}
Here is the text file that the function is reading from:
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,
Now in my root node (app.js), I call the function like so:
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");
}
}
]);
The problem is that the value and name variables are not being printed out to the console in the order that I have put them in. Here is my actual output:
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
And here is my expected output:
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
I believe it has something to do with the synchronicity of it all but I can't for the life of me figure out what it is.
session.sendinstead ofconsole.log?