如何在node.js中的异步函数上正确使用Promise?

时间:2016-11-01 13:38:45

标签: node.js function asynchronous promise

我在节点中有一个异步函数,它读取文本文件,将整个事物放入一个字符串中,在每个新行中拆分字符串,将它们放入一个数组中并随机返回一个。在这里,我实现了一个新的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");
        }
    }
]);

问题是valuename变量没有按照我放入的顺序打印到控制台。这是我的实际输出:

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

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

2 个答案:

答案 0 :(得分:1)

结果将字符返回'\r'从文本文件中带入字符串。将.trim()方法应用于response解决了问题。

答案 1 :(得分:0)

好。所以你的代码中有一点错误。 promise的定义需要2个函数 - resolvereject

但是当你致电承诺时,你会做then()catch()。您在resolve()then() reject()中传递了catch()

所以你要做的就是将最后一段代码更改为:

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

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

我认为这会奏效。