Guest User

Untitled

a guest
Jan 20th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. const fetchWithPromise = (() => {
  2. let promiseCache = {};
  3.  
  4. return function (url, timeout = 2000) {
  5. return promiseCache[url] = promiseCache[url] || (() => {
  6. var timer = setTimeout(function () {
  7. return reject(new Error('Request timed out'));
  8. }, timeout);
  9.  
  10. return Promise.race([timer, simpleCache[url] = fetch(url)
  11. .then(response => response.text())
  12. ]);
  13. })();
  14. }
  15. })();
  16. // Demo Plugin
  17. $.fn.myPlugin = function(url) {
  18. var userdata = fetchWithPromise(url, 2000);
  19.  
  20. this.each(function(e) {
  21. userdata.then(function (data) {
  22. this.innerHTML = data;
  23. });
  24. });
  25. return this;
  26. };
  27.  
  28. // Demo Init Code
  29. $(function() {
  30. $(".element-1").myPlugin('https://raw.githubusercontent.com/callaginn/data/master/array.json');
  31. $(".element-2").myPlugin('https://raw.githubusercontent.com/callaginn/data/master/array.json');
  32. });
Add Comment
Please, Sign In to add comment