我有以下代碼,目前的作品 ,但... 我知道這不是優雅,可以做得更有效率。如何迭代數組,然後回覆用戶使用異步
我想要做的是採取一個電子郵件數組,搜索,如果他們存在與特定templateName相應的數據庫,併爲那些做而不是存在(即是'新'),列出他們回來在返回的頁面上給用戶。但是,如果有很多電子郵件需要檢查,他們最終會等上一段時間。
這是我第一次使用異步,它可能實際上不是實現此目的的最佳方式。下面的一些內容已經根據我實際使用的內容進行了修改,以便於閱讀/遵循。
基本上,我從我的處理程序中調用以下(其中emailArray和templateName都從傳入的請求參數中提取)。
var newEmails = "";
async.eachSeries(emailArray, function(entry, cb) { // check each item in array (these are the potential new emails)
utils.emailAddressAndTemplateExists(entry.toString().toLowerCase(), templateName, function (err, emailExists, templateExists) {
if (emailExists) {
if (templateExists) {
++existingCount;
} else if (emailExists && !templateExists) {
} else {
console.log('template does not exist');
}
} else {
++newCount;
newEmails = newEmails + entry + "</br>";
}
cb();
});
//cb();
}, function (err) {
if (err) { throw err; }
var content = utils.getHTMLHead() + newEmails + utils.getHTMLClose();
utils.writeHTMLPage(response, content);
});
utils調用執行以下操作:(writeHTMLPage只添加所需的html標記併發送回響應)。
//checks for a single email address
var emailAddressExists = function(emailAddress, callback) {
if (emailAddressCollection == null) {
//console.log("it was null " + db_singleton + " " + dbName);
emailAddressCollection = db_singleton.collection(dbName);
}
emailAddressCollection.find({ "emailAddress" : emailAddress.toLowerCase() }).toArray(function (err, docs) {
if (err) { console.err(err); }
if (docs.length == 0) {
callback(null, false, docs.EmailsSent);
} else {
doc = docs[0];
callback(null, true, doc.EmailsSent);
}
});
}
// check for email And template
var emailAddressAndTemplateExists = function (emailAddress, templateName, callback) {
emailAddressExists(emailAddress, function (err, returnVal, templates) {
if (returnVal) {
if (templates != null) {
callback (null, true, templates.hasOwnProperty(templateName)) // email exists, checking for templateName
} else {
callback (null, true, false); // email exists, no templates at all exist
}
} else {
callback (null, false, false); // email does not exist, templates must be false
}
});
}
//creates HTML formated respnse data
function writeHTMLPage(response, content) {
// if (err) { console.error(err); response.send("Error " + err); }
response.writeHead(200, {"Content-Type": "text/html"});
response.write(content);
response.end();
}
什麼是更優雅和高效的方式來做到這一點?