Express Node.JS-接收Redis回调,执行Promise [英] Express Node.JS - Receiving Redis callback, executing promises

查看:63
本文介绍了Express Node.JS-接收Redis回调,执行Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Node/Express路由功能,该功能在另一个模块中执行Redis调用.我想在一个节点模块中执行复杂的Redis功能,并发送一个简单的回调,说路由模块成功了.Redis调用会执行,但是我无法执行任何同步功能,即使从Redis调用中检索甚至是一个简单的true值.这是我的Redis函数:

I have a Node/Express routing function which executes a Redis call in another module. I want to perform a complex Redis function in one node module and send a simple callback saying it is a success to the routing module. The Redis call executes, but I cannot perform any synchronous functions which retrieves even a simple true value from the Redis call. Here is my Redis function:

doctorDB.js

var addDoctor = function addDoctor(id, doc){

    var fields = Object.keys(doc.fields);

    return client.multi()
        .sadd("Doctors", id)
        .hmset(id, "lastName", doc.lastName, "firstName", doc.firstName)
        .hmset(id, "email", doc.email, "university", doc.university, "work", doc.work)
        .sadd(id + ":fields", fields)
        .exec(function(err, replies){
            console.log("It's in this");
            if (doc.middleName){
                console.log("Now here");
                client.hset(id, "middleName", doc.middleName);
                return true;
            } else {
                console.log("Or here");
                return true;
            }                       
        }); 
};

一切都在为此目的进行.现在,我希望将回调发送到Express路由器,以将响应发送到客户端.我希望它采用同步功能的形式,并且我已经尝试使用Q和Async进行许多操作,但是没有任何效果.因此,要么A.我对Promise函数不完全了解,要么B.我不完全将值返回到另一个模块.任何帮助将不胜感激.

Everything is working on that end. Now I want the callback to be sent to the Express router to send a response to the client side. I want it to be in the form of a synchronous function, and I've tried many using Q and Async, but nothing is working. So either A. I don't have a full grasp on promise functions, or B. I don't have a full grasp of returning values to another module. Any help would be appreciated.

作为参考,这是快速路由器端的许多失败尝试:

For reference, here are many failed attempts on the express router end:

routes.js

app.post('/addDoctorInfo',  ensureLoggedIn('/login'), function(req, res, next){

    // function getThis(req){
    //  var deferred = Q.defer();

    //  doctorDB.addDoctor(req.body.id, req.body.doc).then(function(response){
    //      deferred.resolve(response);
    //  }, function(err){
    //      console.log(err);
    //      return deferred.resolve(err);
    //  });
    //  return deferred.promise;
    // }

    // var x = getThis(req);
    // console.log(x);

    doctorDB.addDoctor(req.body.id, req.body.doc).then(function(x){
        console.log(x);
    }).catch(function(err){
        console.log(err);
    }).finally(function(){
        console.log("We made it!");
    });


    // function sendMsg(info){
    //  console.log(info);
    //  res.send({success: true});
    // }
    // async.waterfall([
    //  doctorDB.addDoctor(req.body.id, req.body.doc),
    //  sendMsg(info)
    // ], function(err){
    //  console.log(err)
    // });

    // var DBCALL = doctorDB.addDoctor(req.body.id, req.body.doc);

    // Q.fcall(DBCALL).then(function(x){
    //  return console.log(x);
    // }).catch(function(err){
    //  console.log(err);
    // });
});

推荐答案

我知道了.我使用Q库代替了client.multi().exec()来执行所有功能.这样可以干净地执行所有redis post命令,然后让我检索信息.

I figured this out. I used the Q library to perform all the functions instead of client.multi().exec(). This allowed a clean execution of all the redis post commands and then allowed for me to retrieve the information.

在routes.js文件中,我只有一小段代码.一切都在doctorDB.js文件中执行.

In the routes.js file, I only had a brief bit of code. Everything is executed in the doctorDB.js file.

routes.js

app.post('/addDoctorInfo', ensureLoggedIn('/login'), function(req, res, next){
        return doctorDB.addDoctor(req.body.id, req.body.doc, req, res, next);
});

doctorDB.js

var addDoctor = function addDoctor(id, doc, req, res, next){
    var fields = Object.keys(doc.fields);

    function middleName(id, doc){
        if (doc.middleName){ return client.hset(id, "middleName", doc.middleName); }
        else { return; }
    }

    return Q.all([Q.ninvoke(client, 'sadd', 'Doctors', id),
                    Q.ninvoke(client, 'hmset', id, "lastName", doc.lastName, "firstName", doc.firstName, "email", doc.email, "university", doc.university, "work", doc.work),
                    Q.ninvoke(client, 'sadd', id + ':fields', fields),
                    middleName(id, doc)]).then(function(x){
                        return getInfo(id, req, res, next);;
                    }, function (err) { res.status(404); });
};

这将传递给函数getInfo(),该函数会将响应发送到客户端:

This gets passed on to the function getInfo() which sends a response to the client side:

var redisHGetAll = Q.nbind(client.hgetall, client);

var getInfo = function getInfo(id, req, res, next){
    return redisHGetAll(id).then(function(x){
        return findByMatchingProperties(x);
    }, function (err) { res.status(404); }).then(function(){
        return client.smembers(id + ':fields', function(err, reply){
            data['fields'] = reply;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(data));
        });
    }, function (err) { res.status(404); })
};

function findByMatchingProperties(x) {
    for (var y in x){
        checkData(y, x[y]);
    }       

    function checkData(y, z){
        for (var d in data){
            if (d === y){
                data[d] = z;
            }
        }
    }
}

var data = {
    lastName: null,
    firstName: null,
    middleName: null,
    email: null,
    university: null,
    work: null,
    fields: null
};

这篇关于Express Node.JS-接收Redis回调,执行Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆