1

I tried to use Promise to do that but always got timeout error. All Going to send logged but no SNS 0 has error or SNS 0 has no error logged

function sendSNSMessage(params, index) {
  return new Promise(function (resolve, reject) {
    console.log('Going to send', index, params)
    sns.publish(params, function(err, data) {
      if (err) {
        console.log(`SNS ${index} has error: ${err}`)
        return reject(err)
      }
      console.log(`SNS ${index} has no error: ${data}`)
      resolve(data)
    })
  })
}

exports.query = (event, context, callback) => {
  const connection = mysql.createConnection(config.db)
  try {
    connection.connect(function(err) {
      if (!err) {
        connection.query('SELECT * FROM urls', function(err, results) {
          if (!err) {
            const messsages = results.map((result, index)=>{
              console.log(`results[${index}]: ${result.url}`)
              return sendSNSMessage({
                Message: result.url,
                TopicArn: config.sns.queryArn
              }, index)
            })

            Promise.all(messsages).then(()=>{
              callback(null, 'All messages sent')
            }, console.error)
          } else {
            console.log('Query error!')
            callback(err)
          }
          connection.end()
        })
      } else {
        console.log('Error connecting database ...' + err.message)
      }
    })

  } catch (error) {
    callback(`Exceptiodn: ${error}`)
  }
}

Basically the idea behind is:

  • Do a mysql query to get a couple of records
  • Send one SNS per record tp trigger another lambda function
William
  • 31
  • 4
  • Is your Lambda environment configured correctly to interact with SNS at all? It either needs to be in a VPC on a subnet with a NAT Gateway as its default route, or not in a VPC at all, in order to contact SNS. – Michael - sqlbot Aug 25 '17 at 02:18
  • Yes, it sent one SNS successfully before so I changed to send multiple SNS – William Aug 25 '17 at 03:26
  • This should work if all of your promise stuff is being done correctly. You say a "timeout," but what kind of timeout? The Lambda callback isn't being called, so Lambda execution is timing out? Or some other kind of timeout? Is anything logged? – Michael - sqlbot Aug 25 '17 at 03:35
  • I've update the question, please have a look. – William Aug 25 '17 at 04:16
  • Thanks Michael, you're right. I think I need set up a NAT in the default VPC, thanks a lot! – William Aug 25 '17 at 05:36

0 Answers0