Nodejs等待多个数据库调用

时间:2019-05-22 16:36:57

标签: node.js asynchronous async-await

我正在尝试构造一个需要两个数据库调用的响应。目前,我在使用Node.js的异步/等待功能时遇到了麻烦。

这是主讲课程:

router.get('/:id/mailings', async (req, res) => {

    try {
        const pool = await poolPromise;
        let id = req.params.id;

        const mailings = await getMailings(pool, id);
        const subjectLines = await getSubjectLines(pool, id);

        mailings['subjects'] = await subjectLines;

        await res.json(mailings)
    } catch (err) {
        res.status(500)
        res.send(err.message)
    }
})

这里有两个函数:

async function getMailings(pool, campaignId) {
    const result = await pool.request()
        .query(`
    SELECT [CampaignId] AS campaignId
        ,[MailingId] AS mailingId
        ,[Description] AS description
        ,[HtmlBody] AS htmlBody
        ,[Subjects] AS subjects
        ,[FromLines] AS fromlines
        ,ISNULL(ImageCount, 0) AS imageCount
        ,[InsertTimestamp_utc] AS insertTimestampUTC
    FROM [CampaignHTMLmessage] WHERE [CampaignId] =` + campaignId);

    return result.recordset;
}

async function getSubjectLines(pool, campaignId) {
    const result = await pool.request()
        // .input('input_parameter', sql.Int, req.query.input_parameter)
        .query(`
        SELECT 
            [SubjectLine] as subjectLine
        FROM CampaignSubjectLines WHERE campaignid =` + campaignId);

    return result.recordset;
}

响应是一个空数组,假定响应是在数据库请求完成之前发送的。

1 个答案:

答案 0 :(得分:0)

尝试一下:

HMACSHA256( base64UrlEncode(header) + "." +  base64UrlEncode(payload), secret + UNIQUEIDENTIFIER)

您的异步函数应返回通过执行resolve(valueToReturn)返回的承诺,并将其传递给.then()内部的回调。

这是您的异步​​函数的外观:

  var dataToUpdate;
  await asyncFunction().then( function(data){
      dataToUpdate = data;
  })

  var secondPieceOfData;
  await doStuffWith(dataToUpdate).then(function(data){
      secondPieceOfData = data;
  }

我很确定引擎会自动创建返回新的承诺,但是恕我直言,最好是明确的。