Node JS + AWS Promise Triggered Twice

你离开我真会死。 提交于 2020-12-03 11:35:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!