问题
AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
ses = new AWS.SES();
var params = {};
return ses.sendEmail(params, function (err, data) {
console.log('----->sending email')
}).promise().then((data) => {
console.log('---->sending promise')
}).catch((err) => {
console.log('----->am in error')
console.log(err)
})
Can someone help my above code promise is triggered twice.
I should get below
----->sending email
---->sending promise
But i got
----->sending email
---->sending promise
----->sending email
回答1:
It looks like you are providing both a callback function and using the promise approach. Effectively, this means that you have two different functions that execute when the request is done. Choose one of the following:
You can use the promise approach, with then
and catch
.
function send(params) {
ses.sendEmail(params).promise().then((data) => {
console.log('Email was sent')
}).catch((err) => {
console.log('There was an error')
})
}
You can use promise with async
/await
. Make sure you add the async
keyword to your function header.
async function send(params) {
try {
const data = await ses.sendEmail(params).promise();
console.log('Email was sent')
} catch(err) {
console.log('There was an error')
}
}
Finally, you could use the callback approach:
function send(params) {
ses.sendEmail(params, function(err, data) {
if (err) {
console.log('There was an error')
return
}
console.log('Email was sent')
})
}
来源:https://stackoverflow.com/questions/47635928/node-js-aws-promise-triggered-twice