如何在promise链的末尾将两个单独的查询传递给回调函数?

时间:2018-07-14 17:01:04

标签: javascript sql node.js callback promise

我目前正在尝试在我的诺言链的末尾将两个查询传递给回调函数。我试图将对象和数组传递给最后一个.then()回调,但始终无法检索传入的参数的值。任何人都可以将正确的方向指向我应该做什么或阅读以了解如何做我可以解决我的问题吗?我还附上了记录器的两个屏幕截图。

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));
});

Log Info 1 Log Info 2

1 个答案:

答案 0 :(得分:4)

问题在于您返回的是一个诺言数组,而不是Promise

您所要做的就是返回Promise.all([result, resultLater]);,它将一个promise作为参数,当然会返回一个Promise,当所有内部promise都已解决时,它将解决。

  

Promise.all(iterable)方法返回一个Promise   当可迭代参数中的所有promise具有时解析   解决或可迭代参数不包含任何承诺时。它   拒绝的原因是第一个拒绝的承诺。

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
    /* ... */
});