8000 refactored rpc_client.js · syk-coder/rabbitmq-tutorials@1f64bb0 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1f64bb0

Browse files
committed
refactored rpc_client.js
1 parent 38411ac commit 1f64bb0

File tree

1 file changed

+20
-31
lines changed

1 file changed

+20
-31
lines changed

javascript-nodejs/src/rpc_client.js

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,34 @@
11
#!/usr/bin/env node
22

3-
var amqp = require('amqplib');
4-
var when = require('when');
53

6-
var conn = amqp.connect('amqp://localhost')
7-
conn.then(createChannel).then(null, console.warn);
4+
var amqp = require('amqplib/callback_api');
85

9-
function createChannel(conn) {
10-
return when(conn.createChannel().then(requestFib)).ensure(function() { conn.close(); });
11-
}
6+
var args = process.argv.slice(2);
127

13-
function requestFib(ch) {
14-
var answer = when.defer();
15-
var correlationId = generateUuid();
8+
if (args.length == 0) {
9+
console.log("Usage: rpc_client.js num");
10+
process.exit(1);
11+
}
1612

17-
function maybeAnswer(msg) {
18-
if (msg.properties.correlationId === correlationId) {
19-
answer.resolve(msg.content.toString());
20-
}
21-
}
13+
amqp.connect('amqp://localhost', function(err, conn) {
14+
conn.createChannel(function(err, ch) {
15+
ch.assertQueue('', {exclusive: true}, function(err, q) {
16+
var corr = generateUuid();
17+
var num = parseInt(args[0]);
2218

23-
var ok = ch.assertQueue('', {exclusive: true})
24-
.then(function(qok) { return qok.queue; });
19+
console.log(' [x] Requesting fib(%d)', num);
2520

26-
ok = ok.then(function(queue) {
27-
return ch.consume(queue, maybeAnswer, {noAck: true})
28-
.then(function() { return queue; });
29-
});
21+
ch.consume(q.queue, function(msg) {
22+
console.log(' [.] Got %s', msg.content.toString());
23+
setTimeout(function() { conn.close(); process.exit(0) }, 500);
24+
}, {noAck: true});
3025

31-
ok = ok.then(function(queue) {
32-
console.log(' [x] Requesting fib(30)');
33-
ch.sendToQueue('rpc_queue', new Buffer('30'), {
34-
correlationId: correlationId, replyTo: queue
26+
ch.sendToQueue('rpc_queue',
27+
new Buffer(num.toString()),
28+
{ correlationId: corr, replyTo: q.queue });
3529
});
36-
return answer.promise;
3730
});
38-
39-
return ok.then(function(fibN) {
40-
console.log(' [.] Got %d', fibN);
41-
});
42-
}
31+
});
4332

4433
function generateUuid() {
4534
return Math.random().toString() + Math.random().toString() + Math.random().toString();

0 commit comments

Comments
 (0)
0