我在then语句内调用一个函数,该函数必须等待事件触发,但是我的初始函数几乎立即返回undefined

// call.js
const dialogflow = require('./dialogflow')
module.exports = {
  receive: functions.https.onRequest((request, response) => {
    ...
    let respondToUser = getUserId
      .then((uid) => {
        payload.uid = uid
        dialogflow.handleIncoming(payload).then((result) => {
          console.log(result)
        })
      })
      .then((result) => {
        console.log(result)
        response.end()
      })
    ...
  }
}

// dialogflow.js
module.exports = {
  handleIncoming: (payload) => {
    ...
    let df = dialogflow.textRequest(message.message, {
      sessionId: payload.from
    })
    .on('response', (response) => {
      return response.result.fulfillment.speech
    })
    .on('error', (error) => {
      return 'That\'s an error on my end. Try again later!'
    })
    .end()
  }
}


目标是从dialogflow.handleIncoming(payload)调用call.js,等待它返回一些文本,然后继续。但是,无论我如何构造它,receive都会不断完善,而dialogflow.handleIncoming(payload)最终会成为undefined

我尝试在df上使用诺言没有成功,并且我不知道如何让respondToUser等待handleIncoming的完整响应。其他所有东西都在工作,所以我只包括相关代码。

这使用的是api.ai(对话框流),但如果有帮助,则在Firebase的云函数中使用。感谢任何帮助!

最佳答案

问题是dialogflow.handleIncoming(payload)不是为异步构建的。尝试这个:

// dialogflow.js
exports.handleIncoming = (payload) =>
  new Promise((resolve, reject) => {
    ...
    let df = dialogflow.textRequest(message.message, {
      sessionId: payload.from
    })
    .on('response', (response) => {
      resolve(response.result.fulfillment.speech)
    })
    .on('error', (error) => {
      reject ('That\'s an error on my end. Try again later!')
    })
    .end()
  }

09-19 11:01