异步数据收集与数据记录同步

时间:2016-08-25 20:10:08

标签: javascript node.js asynchronous

澄清问题:如何将数据记录与节点服务器中多个来源的数据收集同步?

var EventEmitter = require('events').EventEmitter,
    emitter      = new EventEmitter();
....
emitter.on('dataLookup', function(request){
    var source1 = new source1();
    source1.lookup(request.id1, function(x){
        request=Object.assign(request, x);
    });
    var source2 = new source2();
    source2.lookup(request.id2, function(x){
        request=Object.assign(request, x);
    });

}).on('writeRequest', function(request, response){
    store.writeRequest(request, function(err){
        if (err){
            log.emit("error",err);
            return;
        } else {
            log.emit("log","request created");
            response.writeHead(200, {'Content-Type': 'text/plain'});
            response.end();
            return;
        }
    });
});

....
var request = {"a":1,"b":2};
....
emitter.emit('dataLookup', request);
emitter.emit('writeRequest', request, response);

注意:dataLookup中有2个呼叫,他们打算异步运行。但是只有在收集完所有数据后才应调用writeRequest

0 个答案:

没有答案