AWS Lambda - как обрабатывать порядок обработки запросов в функции - PullRequest
0 голосов
/ 22 мая 2018

Я использую AWS Lambda (Node.js 8.1) для своего чат-бота AWS Lex, который интегрирован с Facebook и хотел бы узнать, как заставить бота сначала распечатать ответ verifyIntent (запрос 1), а затем распечатать быстрые ответы.(запрос 2).

Я пробовал разные вещи, такие как добавление «запроса 2» в тот же обратный вызов, что и функция verifyIntent, но быстрые ответы всегда печатаются первыми.Я знаю, что проблема заключается в том, что NodeJS является асинхронным, но все еще не знает, как ее решить.

function greeting(intentRequest, callback) {
const hello = intentRequest.currentIntent.slots.Hello;
const sessionAttributes = intentRequest.sessionAttributes || {};
const confirmationStatus = intentRequest.currentIntent.confirmationStatus;

var params = null;

var options = {
            uri: 'https://graph.facebook.com/v2.6/'+PSID+'?fields=first_name,last_name,gender&access_token='+process.env.FB_access_token,
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        };

var options_2 = {
            uri: 'https://graph.facebook.com/v2.6/me/messages?access_token='+process.env.FB_access_token,
            body: JSON.stringify({
                recipient: {"id":PSID},
                message: {
                    text: "Here is a quick reply!",
                    quick_replies: [
                            {
                                content_type: "text",
                                title: "Search",
                                payload: "yes",
                                image_url: "http://example.com/img/red.png"
                            },
                            {
                                content_type: "location"
                            }
                        ]
                }
            }),
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        };

/*request 1 - Get FB user data*/          
request(options, function (error, response, body) {
    console.log(error,response.body);

    body = JSON.parse(body);

    params = {
        first_name: body['first_name'],
    };
    callback(confirmIntent(sessionAttributes, 'GetStarted', 
        {
            Age: null,
        },
        { contentType: 'PlainText', content: 'Hi ' +params.first_name+ ', I will guide you through a series of questions to select your own customized product. Are you ready to start?' }));
});

/*request 2 - Quick replies*/
request(options_2, function (error, response) {
            console.log(error,response.body);
        });
}

Моя функция verifyIntent

function confirmIntent(sessionAttributes, intentName, slots, message) {
return {
    sessionAttributes,
    dialogAction: {
        type: 'ConfirmIntent',
        intentName,
        slots,
        message,
    },
};
}

1 Ответ

0 голосов
/ 22 мая 2018
/*request 1 - Get FB user data*/

request(options, function(error, response, body) {
  console.log(error, response.body);

  body = JSON.parse(body);

  params = {
    first_name: body["first_name"]
  };

  const confirmation = confirmIntent(
    sessionAttributes,
    "GetStarted",
    {
      Age: null
    },
    {
      contentType: "PlainText",
      content:
        "Hi " +
        params.first_name +
        ", I will guide you through a series of questions to select your own customized product. Are you ready to start?"
    }
  );

  /*request 2 - Quick replies*/
  request(options_2, function(error, response) {
    console.log(error, response.body);
    callback(null, confirmation);
  });
});

Вы можете сделать это, чтобы второй запрос всегда выполнялся после первого запроса.

Если у вас есть Node Carbon, вы также можете использовать async await, например:

/*request 1 - Get FB user data*/
const request = require('request-native-promise') //need this for promises (async await are basically promises)
const response1 = await request(options);
const body = JSON.parse(response1.body);

params = {
    first_name: body["first_name"]
};

const confirmation = confirmIntent(
    sessionAttributes,
    "GetStarted", {
        Age: null
    }, {
        contentType: "PlainText",
        content: "Hi " +
            params.first_name +
            ", I will guide you through a series of questions to select your own customized product. Are you ready to start?"
    }
);

callback(null, confirmation);

/*request 2 - Quick replies*/
const response2 = await request(options_2);
...