Advertisement
Guest User

Untitled

a guest
Oct 26th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2. var Bluebird = require('bluebird');
  3.  
  4. // I do not want to wrap this in a coroutine.
  5. function *ping(val) {
  6.     console.log('Ping?');
  7.     yield Bluebird.delay(500);
  8.     pong(val + 1);
  9. }
  10.  
  11. // I do not want to wrap this in a coroutine.
  12. function *pong(val) {
  13.     console.log('Pong?');
  14.     yield Bluebird.delay(500);
  15.     pong(val + 1);
  16. }
  17.  
  18. // Here I want to magically convert a Generator function to a Promise.
  19. Bluebird.coroutine.addYieldHandler(function (gen) {
  20.     if (gen && gen.next && gen.next.call) {
  21.         return Promise.try(function cont(a) {
  22.             var n = gen.next(a);
  23.             if (n.done) {
  24.                 return n.value;
  25.             }
  26.             if (!n.value.then) {
  27.                 return cont(n.value);
  28.             }
  29.             return n.value.catch(gen.throw.bind(gen)).then(cont);
  30.         });
  31.     }
  32. });
  33.  
  34. // This is the main start function.
  35. Bluebird.coroutine(function *() {
  36.     yield ping(10);
  37. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement