node.js 函数调用后 API 的响应范围

Scope of Response of API after function call in node.js

Post API 格式

{
    "first_name": "sakshi",
    "last_name":"agrawal",
    "username":"sakshiagrawallllllll",
    "is_active":"1"
}

来自 POST 的回复 API 如果用户已经注册,那么这将是响应的格式。

{
    "code": 404,
    "message": "User Already In Database"
}

如果用户没有注册,这将是响应。

{
    "code": 200,
    "message": {
        "first_name": "sakshi",
        "last_name": "agrawal",
        "username": "sakshiagrawallllllll",
        "is_active": "1",
        "updated_at": "2021-08-31T06:37:24.536000Z",
        "created_at": "2021-08-31T06:37:24.536000Z",
        "_id": "612dce240e357825b00182d2"
    },
    "count": "",
    "data": ""
}

index.js代码

'use strict';

// Import the Dialogflow module from the Actions on Google client library.
const { dialogflow } = require('actions-on-google');
const functions = require('firebase-functions');
// Instantiate the Dialogflow client.
const app = dialogflow({ debug: true });
const axios = require('axios');

global.username='';
global.firstname='';
global.lastname='';
global.sessionId=0;
global.flag=0;
global.code=[];
global.sid=[];
global.ques=[];
global.response='';
global.res='';
global.data='';
global.rs = '';
global.resp=[];
global.reply = '';

app.intent('Default Welcome Intent', (conv) => {
  conv.add("Welcome to Smart Evaluation world’s largest database of evaluations and interview questions. Are you a registered user ?");
  exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });
    console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
    console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
    function welcome(agent) {
      const sessionVars = {
        'userLang': 'en',  // possibilites handled - 'en', 'hi'
        'words': [],
        'questions': [],
        'currentIndexPosition': 0,
        'score': 0,
      };
      const sessionContext = { 'name': KEY_SESSION, 'lifespanCount': 100000, 'parameters': sessionVars };
      agent.setContext(sessionContext);
      let sessionId = agent.session;
      conv.add(sessionId);
      sessionId=0;
    }
    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    agent.handleRequest(intentMap);
  });
});

app.intent('Non-Registered User', (conv) => {
  console.log(JSON.stringify(conv));
  var userreply = conv.body.queryResult.queryText;
  if (userreply == "no")
  {
    conv.ask("In order to register you I will ask you a series of questions, please give honest feedback. Let’s begin. What is your first name? ");
    flag=0;
  }
  else if (userreply == "yes")
  {
    conv.ask("Welcome back, let’s get you authorized. What is your first name?");
  }
});

app.intent('LastNameIntent', (conv) => {
  firstname = conv.parameters.any;
  conv.ask("What is your last name?" );
});

app.intent('UserNameIntent', (conv) => {
  lastname = conv.parameters.any;
  conv.ask("What is your user name?" );
});

app.intent('SecurityQuestionIntent', (conv) => {
  var reply;
  username = conv.parameters.any;
  conv.ask("Thank you" + firstname + lastname + username);
  if(flag == 0)
  {
    async function makePostRequest() {
      var payload = {
        "first_name": firstname,
        "last_name": lastname,
        "username": username,
        "is_active": "1"
      };
      console.log(payload);
      let res = await axios.post('API', payload, {
      headers: { 'Content-Type' : 'application/json'}
      })
       /*(error) => {
    console.log(error);
    });*/
    console.log("Response of data code is" + res.data.code);
    reply = res.data.code;
    console.log("Reply is " + reply);
    return reply;   
  }
  reply = makePostRequest();
  console.log("Reply after method is" + reply);
  conv.ask(reply);
  }
});

// Set the DialogflowApp object to handle theif() HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);

package.json

{
  "name": "dialogflowFirebaseFulfillments",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "10"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillments",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillments",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "actions-on-google": "^2.4.0",
    "firebase-admin": "^5.13.1",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.6.0",
    "axios": "0.18.0",
    "aws-sdk": "2.696.0",
    "multivocal": "0.15.2",
    "express-session": "1.17.1"
  }
}

当我试图访问函数外部的“reply”变量时,如果尝试在函数内部打印,我会得到 [object Promise] 并且打印良好。

如何在函数外访问变量“reply”。有人可以帮我吗?

这是异步函数的问题。它 returns promise 对象 (refrence):

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

由于 makePostRequest 是异步函数,因此需要使用一些异步构造,例如 thanawait,以获得结果。

我认为最简单的应该是将 reply 赋值和流线更正为 :

编辑:

return 语句添加到 aviod Error: No rersponse has been sent

return makePostRequest().then(reply => {
  console.log("Reply after method is" + reply);
  conv.ask(reply);
})