send_generators.js 969 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env node
  2. 'use strict';
  3. // NB this requires the module 'co':
  4. // npm install co
  5. const co = require('co');
  6. const amqp = require('amqplib');
  7. co(function* () {
  8. // connection errors are handled in the co .catch handler
  9. const conn = yield amqp.connect('amqp://localhost');
  10. // try catch will throw any errors from the yielding the following promises to the co .catch handler
  11. try {
  12. const q = 'hello';
  13. const msg = 'Hello World!';
  14. // use a confirm channel so we can check the message is sent OK.
  15. const channel = yield conn.createConfirmChannel();
  16. yield channel.assertQueue(q);
  17. channel.sendToQueue(q, Buffer.from(msg));
  18. // if message has been nacked, this will result in an error (rejected promise);
  19. yield channel.waitForConfirms();
  20. console.log(" [x] Sent '%s'", msg);
  21. channel.close();
  22. }
  23. catch (e) {
  24. throw e;
  25. }
  26. finally {
  27. conn.close();
  28. }
  29. }).catch(err => {
  30. console.warn('Error:', err);
  31. });