首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >javascript一个回调用于.catch(),另一个回调用于.then()?

javascript一个回调用于.catch(),另一个回调用于.then()?
EN

Stack Overflow用户
提问于 2018-01-11 14:31:40
回答 2查看 100关注 0票数 1

我试图在我的mongodb中注册用户,如果进展顺利,我想给注册用户发送一封电子邮件。为此,我使用sendgrid,它附带了一个.send(msg),它返回承诺.catch(错误)和.then({.})。

如果出现错误,我想发送一个回复到网页,用户已注册,但电子邮件失败。我不能直接从.catch()执行此操作,因为它位于应用程序的另一部分,超出了范围,应该由多个其他函数使用.

sendgrid.js

代码语言:javascript
运行
复制
module.exports.sendRegMail = function (user, password, adminUserID, adminName, success, errorCB) {
    msg.to = email;
    msg.subject = `Welcome ${user.name}! You have been registered!`;
    msg.text = `Dear ${user.name}.\nYou just been registered as a ${user.userType}.\n\nPlease log in with following credentials:\nUsername: ${user.username}\nPassword: ${password}\n\nOBS: it is important that you change your password to a personal one in order to use the platform!\nMost features will be disabled until your account has been secured with a personal password.`;
    sendMail(msg, success, errorCB);
}

function sendMail(msg, success, errorCB){
    sgMail.send(msg)
    .then(() => {
        Logger.logUserAction(userID, name, 'Successfully sent email:\n' + JSON.stringify(msg));
        success();
    })
    .catch(error => {
        Logger.logUserAction(userID, name, 'Tried to send email:\n' + JSON.stringify(msg) + '\nBut failed due to error:\n' + error);
        errorCB();
    });
}

从用户被保存的地方删除..。

代码语言:javascript
运行
复制
 User.addUser(newUser, (err, user) => {
                if (err) {
                    Logger.logAdminAction(decoded.data._id, decoded.data.name, 'Tried to register user: ' + user + '. but failed. Error: ' + err);
                    res.json({ success: false, msg: 'Failed to register user' });
                } else {
                    Logger.logAdminAction(decoded.data._id, decoded.data.name, 'Successfully created user: ' + user);
                    mail.sendRegMail(user, req.body.password, decoded.data._id, decoded.data.name, ()=>{
                        res.json({ success: true, msg: 'User registered, And email sent successfully!' })
                    }, () =>{
                        res.json({ success: true, msg: 'User registered, but email could not be sent! Contact the person manually.' })
                    });  
                }
            });

现在,我试图在sendRegMail()中给出两个回调函数作为参数。然后在.then()中调用一个回调,在.catch()中调用另一个回调,但在我看来,这种方式过于复杂了吗?从父函数中处理承诺错误/成功的正确方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-11 14:35:08

它不起作用,因为您从不称为您的回调。你只需要提到它们(基本上是不操作的)。要打电话给他们,你会让()跟着他们:

代码语言:javascript
运行
复制
function sendMail(msg, success, errorCB){
    sgMail.send(msg)
    .then(() => {
        Logger.logUserAction(userID, name, 'Successfully sent email:\n' + JSON.stringify(msg));
        success();
// ------------^^
    })
    .catch(error => {
        Logger.logUserAction(userID, name, 'Tried to send email:\n' + JSON.stringify(msg) + '\nBut failed due to error:\n' + error);
        errorCB();
// ------------^^
    });
}

,为什么不回承诺呢?

代码语言:javascript
运行
复制
function sendMail(msg) {
    return sgMail.send(msg)
    .then(() => {
        Logger.logUserAction(userID, name, 'Successfully sent email:\n' + JSON.stringify(msg));
        // Nothing particularly useful to return here, so just leave it;
        // the promise will resolve with `undefined`
    })
    .catch(error => {
        Logger.logUserAction(userID, name, 'Tried to send email:\n' + JSON.stringify(msg) + '\nBut failed due to error:\n' + error);
        throw error; // <== Because we haven't *handled* it and want it to propagate
    });
}

然后你就可以像这样使用它:

代码语言:javascript
运行
复制
sendMail("message")
.then(() => { /* it worked */ })
.catch(err => { /* it failed */ });

...and将其构建到链中,并在async函数中使用await和所有其他可以通过简单回调提供的有用功能。

票数 2
EN

Stack Overflow用户

发布于 2018-01-11 14:34:07

你错过了“成功()”和"errorCB()“的括号

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48209455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档