javascript对.catch()的回调和.then()的另一个回调?

时间:2018-01-11 14:31:41

标签: javascript callback promise

我正在尝试在我的mongodb中注册为用户,如果进展顺利,我想向注册用户发送电子邮件。要做到这一点,我正在使用sendgrid,它附带一个.send(msg),它返回一个promise .catch(error)和.then({...})。

如果出现错误,我想向网页发送一个用户已注册的响应,但电子邮件失败了。我不能直接从.catch()那样做,因为它在应用程序的另一部分,超出范围,应该由多个其他函数使用....

sendgrid.js

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();
    });
}

从保存用户的位置切出....

 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()中的另一个回调但是在我看来这样复杂吗?从父函数处理promise错误/成功的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

它不起作用,因为你从不调用你的回调。你只是引用它们(基本上是无操作)。要调用他们,你之后会有()

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();
// ------------^^
    });
}

那说,为什么不回复承诺?

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

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

sendMail("message")
.then(() => { /* it worked */ })
.catch(err => { /* it failed */ });

...并将其构建为链并在async函数中与await一起使用,所有其他有用的东西都提供简单的回调。

答案 1 :(得分:1)

你错过了“success()”和“errorCB()”

的括号