mituri

async/await czyli lepsze promisy

Sep 11th, 2021
1,814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let sayHello = () => {
  2.   return new Promise((resolve) => {
  3.     setTimeout(() => {
  4.       console.log('1. Hello all!')
  5.       resolve()
  6.     }, 500)
  7.   })
  8. }
  9.  
  10. let sayWhatsUp = () => {
  11.   return new Promise((resolve) => {
  12.     setTimeout(() => {
  13.       console.log('2. whats up?')
  14.       resolve()
  15.     }, 500)
  16.   })
  17. }
  18.  
  19. let sayBye = () => {
  20.   return new Promise((resolve) => {
  21.     setTimeout(() => {
  22.       console.log('3. Bye all...')
  23.       resolve()
  24.     }, 500)
  25.   })
  26. }
  27.  
  28. sayHello()
  29.   .then(sayWhatsUp)
  30.   .then(sayBye)
  31.  
  32. // albo zapis z await
  33. await sayHello()
  34. await sayWhatsUp()
  35. await sayBye()
  36.  
  37. console.log('end...')
  38.  
  39. // await musi byc zawsze w asynchronicznej funckcji, bo
  40. // najlepiej spakować to do funkcji async bo innaczej zamrazamy inie linie kodu.
  41. // tak wiec tylko te trzy linijki kodu z await czekaja
  42.  
  43. async function myAsyncFunctions() {
  44.   await sayHello()
  45.   await sayWhatsUp()
  46.   await sayBye()
  47. }
  48.  
  49. myAsyncFunctions()
Advertisement
Add Comment
Please, Sign In to add comment