Я не могу проверить, но попробуйте это для app.post('/', ...
секции
app.post('/', (req, res) => {
const twiml = new MessagingResponse();
app.use(bodyParser());
if (req.body.Body == 'Zoey') {
// Send the message back with last known location.
var body = 'Zoey was last seen in ';
var databaseRef = firebase.database().ref();
databaseRef.once('value')
.then(function (snap) {
// Get the location
var lastLocation = snap.val().lastLocation;
body += lastLocation;
body += ' at ';
// Get the timestamp
var timestamp = snap.val().timestamp;
console.log("at " + timestamp);
body += timestamp;
return body;
})
.then(body => {
twiml.message(body);
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});
} else {
// Bad text message. Send the error message.
var errorMessage = 'Please type Zoey and try again!';
twiml.message(errorMessage);
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
}
}).listen(process.env.PORT || 5000);
Обновление: объяснение
Если вы посмотрите на свой оригинальный код, у вас есть оператор if/else
, используемый для установки сообщения для Twilio. После if / else у вас есть код для отправки ответа.
if (req.body.Body == 'Zoey') {
// go to Firebase
// use data from Firebase to include in message
// it will take some time to receive the response from Firebase
// somewhere in here set the message for Twilio
} else {
// don't go anywhere
// occurring at the same time
// somewhere in here set the message for Twilio
}
// respond to Twilio
// executed immediately
// it does not wait for Firebase to respond
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
Отправка ответа в Twilio без ожидания ответа Firebase - это проблема , поэтому ... давайте посмотрим на раздел Firebase.
var databaseRef = firebase.database().ref();
databaseRef.once('value')
.then(
// execute a function when we get the response from Firebase
// somewhere in here set the message for Twilio
);
Что мы могли бы сделать, это
var databaseRef = firebase.database().ref();
databaseRef.once('value')
.then(
// execute a function when we get the response from Firebase
// return the message for Twilio
)
.then(
// set the message for Twilio, using the argument
// passed by the return of the previous ".then()"
// respond to Twilio
);
Итак, код становится:
if (req.body.Body == 'Zoey') {
// go to Firebase
// use data from Firebase to include in message
var databaseRef = firebase.database().ref();
databaseRef.once('value')
.then(function (snap) {
// execute code when we get the response from Firebase
// return the message for Twilio
// "theMessage" will be passed to the next ".then()"
return theMessage;
})
.then(function (theArgument) {
// execute code when we get the return from the previous ".then()"
// set the message for Twilio, using the argument
twiml.message(theArgument);
// respond to Twilio
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});
} else {
// don't go anywhere, set the message for Twilio
twiml.message("Please type Zoey and try again!");
// respond to Twilio
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
}
Я уверен, что это (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) объясняет обещания лучше меня.
Примечание: Вы можете избавиться от второго .then()
, если переместите код // respond to Twilio
вверх, в конце первого .then()
.