Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. 'use strict';
  2.  
  3. // the wrapper
  4. function addPromiseToCallback(fn) {
  5. const result = function () {
  6. fn(...arguments);
  7. result.resolve([...arguments]);
  8. };
  9.  
  10. result.promise = new Promise((resolve) => {
  11. result.resolve = resolve;
  12. });
  13.  
  14. return result;
  15. }
  16.  
  17. // an example third party function that calls a callback
  18. // in my case this would be the AWS Lambda infrastructure
  19. function callsCallback(cb) {
  20. setTimeout(() => cb('giraffe', Date.now()), 100);
  21. }
  22.  
  23. // my callback function
  24. function myCallback(arg1, arg2) {
  25. console.log(`called back! ${arg1}, ${arg2}`);
  26. }
  27.  
  28. const callbackWithPromise = addPromiseToCallback(myCallback);
  29.  
  30. callsCallback(callbackWithPromise);
  31.  
  32. callbackWithPromise.promise
  33. .then((args) => {
  34. console.log(`Promise 1 resolved with ${args[0]}, ${args[1]}`);
  35. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement