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

标签 node.js function asynchronous promise

我在 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");
        }
    }
]);

问题是 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

我相信这与所有事情的同步性有关,但我一生都无法弄清楚它是什么。

最佳答案

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

关于node.js - 如何在 Node.js 中的异步函数上正确使用 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40361221/

相关文章:

node.js - 如何将socket.io附加到SwaggerExpress

c++ - 将 LPWSTR 转换为 v8::String

node.js - 解析器中的 Angular HttpClient 问题

javascript - 在我的 polyfill 和其他脚本上设置 defer 会保证它们按顺序加载吗?

c# - 异步/等待,调用后更新ui组件, "different thread owns it"异常

javascript - 非法中断语句。 Node.js

javascript - AngularJS运行执行功能?

c++ - C/C++ : getting pointer to function without function name

function - 在 Arduino 代码 (C/C++) 中调用函数时,函数名称前的句点意味着什么?

flutter - 出现异常。 FlutterError (setState() 在 dispose() : _MyProfileState#c3ad1(lifecycle state: defunct, 未安装后调用)