Guest User

Untitled

a guest
Oct 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. var fs = require('fs');
  2.  
  3. function Reader() {
  4. this.content = null;
  5. }
  6.  
  7. Reader.prototype.getContent = function() {
  8. if (this.content === null) {
  9. return new Promise((resolve, reject) => {
  10. console.log('new promise');
  11. fs.readFile('file', 'utf8', function(err, contents) {
  12. if (err) return reject(err);
  13. this.content = contents;
  14. console.log('resolved content', this.content);
  15. resolve(this.content);
  16. });
  17. });
  18. }
  19.  
  20. return Promise.resolve(this.content);
  21. }
  22.  
  23. Reader.prototype.getContent2 = function() {
  24. if (this.content === null) {
  25. this.content = new Promise((resolve, reject) => {
  26. console.log('new promise');
  27. fs.readFile('file', 'utf8', function(err, contents) {
  28. if (err) return reject(err);
  29. this.content = contents;
  30. console.log('resolved content', this.content);
  31. resolve(this.content);
  32. });
  33. });
  34. }
  35.  
  36. return this.content;
  37. }
  38.  
  39. console.log('after calling readFile');
  40.  
  41. var r = new Reader();
  42.  
  43. Promise.all([r.getContent(), r.getContent()])
  44. .then((results) => {
  45. console.log(results);
  46. });
  47.  
  48. Promise.all([r.getContent2(), r.getContent2()])
  49. .then((results) => {
  50. console.log(results);
  51. });
Add Comment
Please, Sign In to add comment