Reputation: 13
I am currently trying to pass two queries to a callback function at the end of my promise chain. I have tried to pass an object and array to the last .then() callback but am never able to retrieve the values of the arguments I pass in. Can anyone point me in the right direction on what I should do or read to understand how I can fix my problem? I have also attached two screenshots of the logger.
mysql.createConnection({
host : ' ',
port : ' ',
user : ' ',
password : ' ',
database : ' '
}).then(function(conn) {
var mysqlDate = new moment(new Date().setDate(12)).add(-4,'h').toDate().toISOString();
mysqlDate = mysqlDate.replace(/[T]/g, ' ').replace(/[Z]/g, '');
mysqlDate = mysqlDate.substring(0, mysqlDate.length - 4);
console.log(`Current date: ${mysqlDate}`);
var query = `SELECT * FROM PredictedTolls WHERE Entry = '${entry}' AND _Exit = '${_exit}' AND DateTime <= '${mysqlDate}' ORDER BY DateTime DESC LIMIT 1`;
console.log(`Current Time Query: ${query}`);
var result = conn.query(query);
var mysqlLater = new moment(new Date().setDate(12)).add(-4, 'h').add(30, 'm').toDate().toISOString();
mysqlLater = mysqlLater.replace(/[T]/g, ' ').replace(/[Z]/g, '');
mysqlLater = mysqlLater.substring(0, mysqlLater.length - 4);
console.log(`Later date: ${mysqlLater}`);
var queryLater = `SELECT * FROM PredictedTolls WHERE Entry = '${entry}' AND _Exit = '${_exit}' AND DateTime <= '${mysqlLater}' ORDER BY DateTime DESC LIMIT 1`;
console.log(`Future Time Query: ${queryLater}`);
var resultLater = conn.query(queryLater);
console.log(`Result Later: ${resultLater}`);
conn.end();
return [result, resultLater];
}).then(function(rows) {
console.log(rows);
var dateTime = rows[0].DateTime;
var toll = rows[0].PredictedToll;
console.log(`Best time: ${dateTime}`);
options.speechText = `The best time to leave is <say-as interpret-as='spell-out'>${dateTime}</say-as> with a toll of <say-as interpret-as='spell-out'>${toll}</say-as>. `;
options.endSession = true;
context.succeed(buildResponse(options));
});
Upvotes: 1
Views: 54
Reputation: 40404
The problem is that you're returning an Array of promises, not a Promise
.
All you have to do is return Promise.all([result, resultLater]);
, that takes an array of promises as argument, and of course returns a Promise
that will resolve when all the internal promises have been resolved.
The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
mysql.createConnection({
host : ' ',
port : ' ',
user : ' ',
password : ' ',
database : ' '
}).then(function(conn) {
/* ... */
return Promise.all([result, resultLater]);
}).then(function(rows) {
console.log(rows);
// rows will have [result, resultLater] resolved values
/* ... */
});
Upvotes: 4