Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. // A promise implementation that enables sequencing and flattening of an arbitrary
  2. // number of asyncronous functions, and allows a value to be passed through.
  3.  
  4. function first() {
  5. return promise(function(resolve, val) {
  6. setTimeout(function() {
  7. console.log("first", val);
  8. resolve(2);
  9. }, 50);
  10. });
  11. }
  12.  
  13. first().then(function(resolve, val) {
  14. setTimeout(function() {
  15. console.log("second", val);
  16. resolve(val+1);
  17. }, 110);
  18. }).then(function(resolve, val) {
  19. setTimeout(function() {
  20. console.log("third", val);
  21. resolve((val+1)*10);
  22. }, 60);
  23. }).then(function(resolve, val) {
  24. setTimeout(function() {
  25. console.log("fourth", val);
  26. resolve();
  27. }, 40);
  28. }).end();
  29.  
  30. console.log("zeroth");
  31.  
  32. // The code will output:
  33. // zeroth
  34. // first initVal
  35. // second 2
  36. // third 3
  37. // fourth 40
  38.  
  39. function promise(f) {
  40. function callFns(arr, val) { // Call functions in order and pass the val argument
  41. if (arr.length == 1) {
  42. return arr[0](function() {}, val);
  43. } else {
  44. arr[0](function(n) { // n is the resolve argument
  45. callFns(arr.slice(1), n);
  46. }, val);
  47. }
  48. }
  49. var fns = [f]; // List of functions to call
  50. var res = {
  51. then: function(next) {
  52. fns.push(next);
  53. return res; // Recursively enable an arbitrary number of then-calls
  54. },
  55. end: function() {
  56. callFns(fns, "initVal"); // Pass all functions to be called together
  57. // with 'val' for the first of them.
  58. }
  59. };
  60. return res;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement