简体   繁体   English

node.js解析promise并返回值

[英]node.js resolve promise and return value

I use the Microsoft bot framework to come up with a "simple" PoC bot. 我使用Microsoft bot框架来提出一个“简单”的PoC机器人。 I used a tutorial as a basis and extend it. 我使用教程作为基础并扩展它。

I've a couple of basic functions for differet intents (ie. greetings, goodbye, etc) and one with some more logic in it (reqstatus). 我有几个不同意图的基本功能(即问候,再见等)和一个有更多逻辑的功能(reqstatus)。

The simple ones (ie greeting.js) return the answer nicely but the more complex one doesn't (reqstatus.js). 简单的(即greeting.js)很好地返回答案,但更复杂的答案(reqstatus.js)。 Running the main code of reqstatus.js (without the first "const getReqStatus = (entity) => {") in a standalone script works. 在独立脚本中运行reqstatus.js的主代码(没有第一个“const getReqStatus =(entity)=> {”)。

server.js (main) -> see call in "if (intent) {"... server.js (main) - >请参阅“if(intent){”中的调用...

const getFeelings = require('./intents/feelings.js')
const getGoodbyes = require('./intents/goodbyes.js')
const getGreetings = require('./intents/greetings.js')
const getHelp = require('./intents/help.js')
const getReqStatus = require('./intents/reqstatus.js')
... 
const bot = new builder.UniversalBot(connector)

// Intents based on definitions on recast
const INTENTS = {
  feelings: getFeelings,
  goodbyes: getGoodbyes,
  greetings: getGreetings,
  help: getHelp,
  reqstatus: getReqStatus,
}

// Event when Message received
bot.dialog('/', (session) => {
  recastClient.textRequest(session.message.text)
  .then(res => {
  const intent = res.intent()
  const entity = res.get('request_number')

  console.log(`UserName: ${session.message.user.name}`)
  console.log(`Msg: ${session.message.text}`)
  console.log(`Intent: ${intent.slug}`) 

  if (intent) {
    INTENTS[intent.slug](entity)
    .then(res => session.send(res)) 
    .catch(err => session.send(err))
  }
  })
  .catch(() => session.send('Sorry I didn\'t get that. '))
  })
  ...

greetings.js -> Returns the string ok greetings.js - >返回字符串ok

const getGreetings = () => {
  const answers = ['Hi, my name is SuperBot. Nice to meet you!', ] 
  return Promise.resolve((answers))
  }
module.exports = getGreetings

reqstatus.js -> Does not return anything reqstatus.js - >不返回任何内容

const getReqStatus = (entity) => {
  var request = require('request');
  var request_number = entity.toLowerCase()
  var output = [];


  // Processing
  var lineReader = require('readline').createInterface({
  input: fs.createReadStream('netreqs.csv')
  }); 

  lineReader.on('line', function (line) {
  var jsonFromLine = {};
  var lineSplit = line.split(';');
  jsonFromLine.req = lineSplit[0];
  jsonFromLine.req_count = lineSplit[1];
  jsonFromLine.req_type = lineSplit[2];
  //...
  var req_lowever = jsonFromLine.req.toLowerCase()
  if (req_lowever == request_number) {
     output.push( `Your request ${jsonFromLine.req} was received`);    
  // simplified
  }
  });

  // Output
  lineReader.on('close', function (line) {
  if (output == '') {
    output.push( `I was not able to find a request like ${request_number}.`);
    }
  console.log(output); // list output 
  return Promise.resolve(output); 
   });
  }
module.exports = getReqStatus

I also tried to put getReqStatus in a function but that also didn't work. 我也尝试将getReqStatus放在一个函数中但是也没有用。 After a lot of trying and googling I'm still stuck and wanted to ask the experts here. 经过大量的尝试和谷歌搜索,我仍然卡住了,并想在这里问专家。 Thanks a lot in advance. 非常感谢提前。

I think that the problem is that your getReqStatus isn't really returning anything. 我认为问题是你的getReqStatus并没有真正返回任何东西。 In your example getGreetings function you're actually returning Promise.resolve(answers) as the return value of that function. 在您的示例getGreetings函数中,您实际上将Promise.resolve(answers)作为该函数的返回值返回。

However, in your getReqStatus function, you just set up a listener lineReader close event: 但是,在getReqStatus函数中,您只需设置一个侦听器lineReader close事件:

lineReader.on('close', function (line) {
if (output == '') {
    output.push( `I was not able to find a request like ${request_number}.`);
}
    console.log(output); // list output 
    return Promise.resolve(output); 
});

You're returning a Promise resolved inside the anonymous callback function you're passing to lineReader.on() as second parameter. 你将你传递给lineReader.on()作为第二个参数的匿名回调函数中返回一个Promise。 That is not the return value from the getReqStatus function itself, so that getReqStatus is not returning anything, as expected. 这不是getReqStatus函数本身的返回值,因此getReqStatus没有按预期返回任何内容。

The code of that function runs correctly as standalone code, as you say, just because it sets the listener properly and it does what it has to do. 正如你所说,该函数的代码作为独立代码正确运行,只是因为它正确地设置了监听器并且它完成了它必须做的事情。 However, that code just doesn't return a Promise when wrapped in a function. 但是,该代码在包装在函数中时不会返回Promise。

What you would need is to return a Promise that wraps the lineReader.on close handler, like: 你需要的是返回一个包含lineReader.on关闭处理程序的Promise,如:

function getReqStatus(){
//...code

return new Promise( function(resolve , reject ){
    lineReader.on('close', function (line) {
        if (output == '') {
            output.push( `I was not able to find a request like ${request_number}.`);
        }
        console.log(output); // list output
        return resolve(output);
        });
    });
}

I say would because I really don't know if this code will work, I don't have any kind of experience with the Microsoft Bot framework and not used at all with the readline module. 我说因为我真的不知道这段代码是否有效,我对Microsoft Bot框架没有任何经验,而且根本没有使用readline模块。 However, even if this doesn't solve your problem, I hope it will help you a bit understanding why your function doesn't return a Promise and how could you fix it. 但是,即使这不能解决您的问题,我希望它能帮助您理解为什么您的函数不返回Promise以及如何解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM