2015-04-21 41 views
0

我有以下代碼,目前的作品 ,但... 我知道這不是優雅,可以做得更有效率。如何迭代數組,然後回覆用戶使用異步

我想要做的是採取一個電子郵件數組,搜索,如果他們存在與特定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(); 
} 

什麼是更優雅和高效的方式來做到這一點?

回答

0

這看起來像它是根據你通常看到它的方式構建的。你可以看看與ES6承諾,以獲得更好的程序流程:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

基本上,它可以讓你鏈在一起的功能。這對你現在正在做的事情並不是太壞,它可能會幫助一些人,但是如果你有4-5個回調嵌套在一起,那麼承諾可以是非常有用的。

你只需要通過不同的結構化代碼來使用Promise,但它會使「回調地獄」的問題更少。

相關問題