2

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.

6
  • Can you try without "return" in return resolve(response); and return reject(err); Commented Nov 1, 2016 at 13:46
  • @donlys I have tried this and unfortunately it produces the same outcome :( Commented Nov 1, 2016 at 13:50
  • Can you try then clause with just then(function(value){console.log(value + ", " + name);}).catch(function(reason){console.log(reason)}) Commented Nov 1, 2016 at 13:53
  • @donlys Still not working :9 Commented Nov 1, 2016 at 13:56
  • Have you tried session.send instead of console.log? Commented Nov 1, 2016 at 15:41

2 Answers 2

1

Turns out the character returns '\r' were being brought into the string from the text file. Applying the .trim() method to the response solved the problem.

Sign up to request clarification or add additional context in comments.

Comments

0

Okay. So there is a little error in your code. The definition of promise takes 2 functions - resolve and reject.

But when you call the promise, you do a then() and catch(). You pass resolve() in then() and reject() in catch().

So all you have to do is change the last bit of code to this:

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

}).catch(function(reason) {
    console.log(reason);
});

I think this will work.

7 Comments

Unfortunately, this doesn't work. The output is still the same - my name is bring printed first and the value of the Promise is then being printed on top/next to it.
@blueprintChris my output is this: ➜ Desktop node text.js I will remember your name, , Chris ➜ Desktop node text.js Howdy, , Chris ➜ Desktop node text.js Hello there, , Chris ➜ Desktop node text.js Nice to meet you , Chris ➜ Desktop node text.js I will remember your name, , Chris ➜ Desktop node text.js Thanks , Chris ➜ Desktop
The file you pasted here and the code that you posted here, work with what I changed. Please check your code or file.
@blueprintChris Where is the code for logging "my name is chris"? I think some code is missing.
I edited and added more code, maybe it is to do with the function that the function call is within? I'm not sure.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.