【问题标题】:Node JS + AWS Promise Triggered TwiceNode JS + AWS Promise 触发两次
【发布时间】:2018-05-18 01:40:41
【问题描述】:
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)
})

谁能帮助我上面的代码承诺被触发两次。

我应该在下面

----->发送电子邮件

---->发送承诺

但我明白了

----->发送电子邮件

---->发送承诺

----->发送电子邮件

【问题讨论】:

    标签: javascript node.js amazon-web-services aws-sdk


    【解决方案1】:

    看起来您既提供了回调函数又使用了 Promise 方法。实际上,这意味着您有两个不同的函数在请求完成时执行。选择以下选项之一:

    您可以使用承诺方法,thencatch

    function send(params) {
        ses.sendEmail(params).promise().then((data) => {
            console.log('Email was sent')
        }).catch((err) => {
            console.log('There was an error')
        })
    }
    

    您可以将 promise 与 async/await 一起使用。确保将 async 关键字添加到函数头。确保您的 Node 运行时支持 async/await,或者您的代码被转换为您使用的任何 Node 版本。

    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')
        }
    }
    

    最后,你可以使用回调方法:

    function send(params) {
        ses.sendEmail(params, function(err, data) {
            if (err) {
                console.log('There was an error')
                return
            }
            console.log('Email was sent')
        })
    }
    

    【讨论】:

    • 谢谢伙计...它现在工作...现在我知道我有多愚蠢
    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2017-09-30
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多