Advertisement
ur001

Untitled

Sep 17th, 2019
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * SetTimeout
  3.  */
  4. // 1 ==================================================
  5. (function() {
  6.   console.log(1);
  7.   setTimeout(function () { console.log(2) }, 1000);
  8.   setTimeout(function () { console.log(3) }, 0);
  9.   console.log(4);
  10. })();
  11. // 2 ==================================================
  12. // 0 - 4
  13. for (let i = 0; i < 5; i++) {
  14.   setTimeout(function () { console.log(i) }, i*1000);
  15. }
  16. // 5*5
  17. for (var j = 0; j < 5; j++) {
  18.   setTimeout(function () { console.log(j) }, j*1000);
  19. }
  20. /**
  21.  * Объекты
  22.  */
  23. // 1 ==================================================
  24. // 26
  25. const o = { b: 25 };
  26.  
  27. const foo1 = (obj) => {
  28.   obj.b = 26;
  29. };
  30.  
  31. foo1(o);
  32. console.log(o.b);
  33. // 2 ==================================================
  34. var a = {};
  35. var b = {key: 'b'};
  36. var c = {key: 'c'};
  37. console.log('a: ', a);
  38. console.log('b: ', b);
  39. console.log('c: ', c);
  40. a[b] = 123;
  41. a[c] = 156;
  42.  
  43. console.log(a[b]); // Объект преобразуется в строку [object Object], которая и становится ключом. Итог 156.
  44. /**
  45.  * Функции
  46.  */
  47. function sum(a, b) {
  48.   if (b) return a + b;
  49.   var currentSum = a;
  50.  
  51.   function f(c) {
  52.     currentSum += c;
  53.     return f;
  54.   }
  55.   f.toString = () => currentSum;
  56.   return f;
  57. }
  58.  
  59. console.log(sum(2,3)); // 5
  60. console.log(sum(2)(3)); // 5
  61. /**
  62.  * Ассинхронные функции
  63.  */
  64. function resolveAfter2seconds(x) {
  65.   return new Promise(resolve => {
  66.     setTimeout(() => {
  67.       resolve(x);
  68.     }, 1000);
  69.   });
  70. }
  71. function resolveAfter5seconds(x) {
  72.   return new Promise(resolve => {
  73.     setTimeout(() => {
  74.       resolve(x);
  75.     }, 5000);
  76.   });
  77. }
  78. // парарллельно
  79. async function addParallel(x) {
  80.   const a = resolveAfter2seconds(20);
  81.   const b = resolveAfter5seconds(30);
  82.   return  x + await a + await b;
  83. }
  84. // последовательно
  85. async function add(x) {
  86.   const a = await resolveAfter2seconds(20);
  87.   const b = await resolveAfter5seconds(30);
  88.   return  x + a + b;
  89. }
  90. add(10).then(result => console.log(result));
  91. addParallel(10).then(result => console.log(result));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement