Javascript 带回调和参数的函数

Javascript Function with Callback and Parameters

我 运行 在尝试添加需要 运行 另一个带参数的函数的回调时遇到一些基本 JS 函数的问题。

这是我的电子邮件功能:

function sendEmail(template, to, cc, bcc, callback, optional=null){

// Define vars needed
var body = '',
    subject = '';

// Based on the template..
switch(template){

    case 'privateNote':

        // Define the subject
        subject = 'Tool Request - Private Note Added';

        // Define our body
        body += 'Hello, <br /><br />';
        body += 'A new private note has been added to Request #' + requestID + '.<br/><br/>';
        body += 'To visit the request, click the following link: <a href="' + window.location.protocol + "//" + window.location.host + "/tool/Request2.php?id=" + requestID + '">' + window.location.protocol + "//" + window.location.host + "/tool/Request2.php?id=" + requestID + '</a>.';
        body += '<br /><br />';
        body += '<em>Message created by ' + userFirst + ' ' + userLast + '</em>';

}

// Send our email
$.ajax({
    url: "../resources/Classes/class.email.php",
    type: "POST",
    cache: false,
    data: {
        from: "noreply@domain.com",
        to: to,
        cc: cc,
        bcc: bcc,
        subject: subject,
        body: body
    },
    error: function(err) {
        alert(err.statusText);
    },
    success: function(data) {
        // Handle Callback
        callFunction(callback);
    }
});
}

// Callbacks
function callFunction(func) {
    func();
}

// Reload the page
function refresh(){
    location.reload('true');
}

我是这样使用函数的:

sendEmail('privateNote', toArray, '', '', refresh, obj);

一切正常,但我遇到了问题。

有一个部分我需要同时发送两封电子邮件,一封给添加到请求中的人,一封给那些从请求中删除的人。

我尝试做的是:

var remove = sendEmail('privateNote', toArray, '', '', refresh, obj);

// Trigger Email to those who are added to the request
// However, I was trying to send a the other email with params as a callback instead of refreshing the page.

sendEmail('privateNote', toArray, '', '', remove, obj);

这样做的问题是它似乎同时触发了两个,而没有等待一个完成导致一些异步问题。

有没有办法正确地做到这一点?我知道这可能不是处理电子邮件的最佳方式,但到目前为止,每次只需处理一封电子邮件,一切都运行良好。

这会立即调用 sendEmail() 函数:

var remove = sendEmail('privateNote', toArray, '', '', refresh, obj);

因为 sendEmail() 没有 return 任何东西,所以 removeundefined

要使其成为正确的回调,请将其包装在 function():

var remove = function() {
  sendEmail('privateNote', toArray, '', '', refresh, obj);
}