2017-05-24 82 views
0

我正在嘗試使用節點和快車製作API。 這是創建用戶的功能。如何避免級聯承諾和catchs?

我不確定我是否正確處理錯誤,因爲異步mongodb函數,我覺得自己處於「承諾地獄」。我要做的下一件事是讓插入用戶的ID,我想這將是另一個諾言,另一個錯誤來處理......

exports.create = function(req, res, next) { 
    var errors = []; 
    var userData = req.body; 

    // exit if the user didn't fill all fields 
    var requiredFields = ['first_name', 
         'last_name', 
         'login', 
         'email', 
         'password', 
         'sex']; 
    requiredFields.forEach(function(elem) { 
    if (!userData.hasOwnProperty(elem)) 
     errors.push('The field \'' + elem + '\' is missing'); 
    }); 
    if (errors.length !== 0) 
    res.status(400).json({errors: errors}); 

    // check if the user or the login are already in use 
    db.connection.collection(COLLECTION_NAME).findOne({ $or: [ 
           { email: userData.email }, 
           { login: userData.login } 
          ]}) 
    .then(function(data) { 
     // if there is no user (null) we can create it 
     if (data === null) { 
     db.collection(COLLECTION_NAME).insertOne(userData).then(function (data) { 
      res.status(201).json("success"); 
     }, function (err) { 
      res.status(400).json({errors: ["DB error: cannot create user"]}); 
     }) 
     } else { 
     errors.push('An user is already registered with this email or this login.'); 
     if (errors.length !== 0) 
      res.status(400).json({errors: errors}); 
     } 
    }, function (err) { 
     res.status(400).json({errors: errors}); 
    }) 
} 

有沒有做到這一點最好方法是什麼?

順便說一下,我不能使用驗證庫,也不能使用貓鼬。

謝謝。

+0

可以返回當時的語句中一個新的承諾... –

+0

看一看https://stackoverflow.com/questions/27715275/whats-該差之間,返回值有或承諾,解決從 - 然後 –

回答

1
// check if the user or the login are already in use 
    db.connection.collection(COLLECTION_NAME).findOne({ 
         $or: [ 
          { email: userData.email }, 
          { login: userData.login } 
]}) 
.then(function(data) { 
    // if there is no user (null) we can create it 
     if (data === null) { 
     return db.collection(COLLECTION_NAME).insertOne(userData) 
    }else{ 
     return new Promise.reject(0);//throw the error 
    } 
}).then(function (data) { 
     res.status(201).json("success"); 
}, function (err) { 
     res.status(400).json({errors: ["DB error: cannot create user"] 
}); 

你可以鏈中的承諾...