承诺处理 – 更新数据库条目,如果存在

我坚持对Promises的新挑战。

目标:仅在P_KEY存在的情况下更新数据库条目。

当前的数据库是通过模块公开的,模块已经为db获取和放置方法。 双方都回诺言。

做法:

  1. API调用节点js上具有ID和值集的更新方法处理程序(json)
  2. 在post方法的处理程序中调用get db模块的方法检查promise成功的值是否为空,如果是则返回false否则为true。
  3. 如果属实; 数据存在调用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 ,不pipe元素是否存在或不相同的结果。 未find。

我能做些什么来纠正?

一个问题是没有价值是从checkIfPKExists()函数调用返回,请参阅为什么值未定义在.then()链接到承诺? 。 使用.catch() .then().catch()来获取函数返回的Promise

 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 }) 

checkIfPKExists()是一个asynchronous函数,如果你想使用ch,你将不得不使用.then()函数来获取它,然后使用该值。

 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); }) }})