我尝试使用Promise来做到这一点,但总是出现超时错误。已记录所有Going to send
但未记录SNS 0 has error
或SNS 0 has no error
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}`)
}
}
基本上背后的想法是: