2017-08-12 40 views
2

我對承諾的新挑戰卡住了。承諾處理 - 更新數據庫條目(如果存在)

目標:僅在存在P_KEY時更新數據庫條目。

當前數據庫是通過模塊公開的,模塊已經獲取和放置db的方法。雙方都回諾言。

方法:

  1. API調用的更新方法處理節點JS用ID和組值(JSON)
  2. 在處理程序後方法調用數據庫模塊檢查get方法,如果在承諾值如果是,則成功爲空或返回false否則爲真。
  3. 如果爲true;數據存在調用put db模塊的方法。

但以某種方式數據它總是返回false。即使db入口已經通過db api進行了。

/** Function to check if p_key exist*/ 
function checkIfPKExists(idVal){ 
    pkdb.get(idVal).then(function(value){ 
    if(value){ 
     return true; 
    } else { 
     return false; 
    } 
    }, 
    function(err){ 
    console.log(err); 
    return false; 
    }) 
} 

/** UPDATE METHOD **/ 
var ch = checkIfPKExists("p_k"+req.body.id); 
if(!ch){ 
    res.send("pk does not exist oo " + req.body.id); 
} else { 
    var pk_promise = pkdb.put("p_k"+req.body.id, req.body.pk); 
    pk_promise.then(
    function(){ 
     res.send(JSON.stringify(req.body.pk) + "Updated Successfully"); 
    }, 
    function(err){ 
     res.send("Error occurred : " + err); 
    } 
) 
} 

我的理解是ch值從checkPK功能,因爲這就是設置一個承諾,它只是向前走並處理if環在默認情況下代表true,也不論做元素是否存在還是不一樣的結果。未找到。

我能做些什麼來糾正它?

回答

0

一個問題是沒有價值爲checkIfPKExists()函數調用return版,見Why is value undefined at .then() chained to Promise?。使用.then().catch()擺脫功能

function checkIfPKExists(idVal) { 
    // `return` the `Promise` here 
    return pkdb.get(idVal).then(function(value) { 
    if (value) { 
     return true; 
    } else { 
     return false; 
    } 
    }, function(err) { 
    console.log(err); 
    return false; 
    }) 
} 

/** UPDATE METHOD **/ 
var ch = checkIfPKExists("p_k" + req.body.id); 

ch.then(function(bool) { 
// if `true` do stuff 
if (bool) { 
    var pk_promise = pkdb.put("p_k" + req.body.id, req.body.pk) 

    return pk_promise.then(function() { 
    return res.send(JSON.stringify(req.body.pk) + "Updated Successfully"); 
    }, function(err) { 
    return res.send("Error occurred : " + err); 
    }) 
} else { 
    // do other stuff 
    return res.send("pk does not exist oo " + req.body.id); 
}) 
.catch(function(err) { 
    // handle error 
}) 
+0

謝謝你的回答。這真的幫助我理解更好的承諾。不錯的代碼流。 –

0

checkIfPKExists()是一個異步功能,如果你想使用CH你將不得不使用一個。那麼()得到它在一個函數,然後使用該值。

function checkIfPKExists(idVal) 
{ 
    return pkdb.get(idVal).then(function(value) 
    { 
     if(value) 
     { 
      return true;} 
     else 
     { 
      return false; 
     }   
    }, function(err) 
    { console.log(err); 
      return false; 
    }) 
} 

/** UPDATE METHOD **/ 
checkIfPKExists("p_k"+req.body.id).then(function(ch){ 
    if(!ch) 
    { 
     res.send("pk does not exist oo " + req.body.id); 
    } 
    else 
    { 
     return pkdb.put("p_k"+req.body.id, req.body.pk).then(
      function() 
      { 

       res.send(JSON.stringify(req.body.pk) + "Updated Successfully"); 

      }, 
      function(err) 
      { 

       res.send("Error occurred : " + err); 
      }) 
}}) 
+0

注意返回Promise價值,沒有價值從'checkIfPKExists()返回'在代碼的函數調用在回答 – guest271314

+0

@ marvel308它回答我的問題。我贊成答案,但沒有反映,因爲我代表<15代表。我感謝你的時間和幫助。謝謝! –