2016-09-23 22 views
0

所以我有一個運行一些其他異步函數的函數,我想知道什麼是處理錯誤的最佳方法,以及如果我是「正確的方式」。運行Async函數的函數是否被認爲是Async本身?以及如何處理它的錯誤?

基本上,這個函數的作用是:

  1. 收到「型號」,對象的屬性與要傳遞到架構和一個回調函數(我不知道如果我需要,或者在這種情況下是最佳實踐)。

  2. 然後我檢查輸入(查看註釋),在一種情況下,我使用文件系統模塊(異步),因爲我想只在需要時才需要模型。

  3. 然後,我嘗試將其全部保存到數據庫,該數據庫也是異步的。

快速提示:我正在使用Mongoose來處理數據庫。

/* *將新條目添加到數據庫的功能。 *此功能取決於各種異步功能, *因此我們希望收到一個回調函數以更好地處理錯誤。 * *預計: * modelName =要使用的模型的名稱。 * properties =要傳遞給模型模式的對象。 *回調=上面解釋。 */ 函數add(MODELNAME,性質,回調){

// If a callback wasn't passed, throw error. 
if (typeof callback !== 'function') { 
    return callback(new Error('Model Add function should receive a callback')); 
} 

/* 
* The variable 'properties' is not required, so only if declared 
* we'll check if it is an object. 
* IMPORTANT: Needs to be fixed! 
*/ 
if (typeof properties !== 'object') { 
    return callback(new Error('Properties passed should be an Object')); 
} 

/* 
* Checking modelName is an existing model by checking if a file with that 
* name exists in the models directory. 
* 
* This is an asynchronous so we handle the output(which can result in an error) 
* using a callback. 
*/ 
fs.access(`./models/${modelName.toLowerCase()}.js`, fs.constants.F_OK, err => { 

    // If an error is returned it means that the file does not exists. 
    if (err) { 
     return callback(new Error(`There is no Model "${modelName}"`)); 
    } 

    // Require the model file. 
    require(`./${modelName.toLowerCase()}`); 

    // Getting the model. 
    let Model = mongoose.model(modelName); 
    let document = new Model(properties); 

    // Saving the new "document" to the database. 
    document.save(err => { 
     if (err) { 
      return callback(new Error(`Error while saving "${modelName}" to the Database: ${err}`)); 
     } 

     // For debugging purposes... 
     console.log(`A new ${modelName} was successfully saved to the database`); 
    }); 

}); 

}

正如你所看到的,我已經在這裏嵌套的異步功能,我覺得它可以做一個更好的辦法。

任何想法?這是處理數據庫任務的正確方法嗎?

謝謝!

+1

只是出於好奇,你的服務器上使用這個(與快遞爲例)和你在每次請求執行這個功能呢?如果是,訪問文件系統並且每個請求需要模塊將會對性能產生巨大影響。此外,錯誤處理存在不一致。在一種情況下,你拋出的異常將會使程序崩潰,而另一種情況是你在回調中返回錯誤。我認爲值得看看這裏的錯誤處理: [錯誤處理](https://nodejs.org/api/errors.html) –

+0

正如Svabael寫道,這可能是一個巨大的問題。我不明白,爲什麼要生成模型?我很好奇。如果您需要基於用戶活動創建自定義模型,則基於此您缺少擁有NoSQL數據庫的要點。 – manuerumx

+0

感謝您的建議,我不會在現場服務器或任何其他應用程序上使用此功能,我只是在嘗試構建一個小型項目以獲得更好的效果。關於錯誤 - 我正在檢查什麼是最好的方法,但是我更新了上面的代碼到我目前使用的代碼,但是我仍然在尋找處理這些錯誤的「正確方法」。當我想添加一些東西到數據庫時,這個函數將會運行,例如,「post」或類似的東西。性能要求所有模型提前更好嗎? –

回答

1

幾件事我注意到:

if (typeof callback !== 'function') { 
    return callback(new Error('Model Add function should receive a callback')); 
} 

你怎麼能指望調用回調說,沒有回調?

// Require the model file. 
require(`./${modelName.toLowerCase()}`); 

require()同步 - 從來沒有把它叫做一個異步函數中。它可能會被緩存,只會在第一次調用時(每個模型)阻塞,但它會阻止整個服務器。

在任何情況下,這個問題可能會更適合https://codereview.stackexchange.com/

+0

沒想到......我應該在這種情況下拋出異常嗎? –

相關問題