在 redis 模块中,遇到一个苦难的问题,它的全部get方法都是经过 callback 来取值的。可是实际的状况下,又遇到一个,我设置值前,须要先经过 exists 检查一下 key 是否存在。node
能够经过返回一个 Promise 对象来解决这个问题。git
以下:github
function testG(req, res) { co(function *() { let token = req.query.token || common.ranStr(); let uniqueToken = yield generateToken(token); console.log(uniqueToken); res.send({uniqueToken}); }); } function generateToken(token) { return new Promise(function (resolve, reject) { redisHelper.exists(token, function (err, exists) { if (err) { reject(err); } else { resolve(exists); } }); }); }
----------------------------------------redis
Another Example: https://github.com/alsotang/node-lessons/tree/master/lesson17less