Advertisement
CSenshi

t1

Oct 6th, 2023
876
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. There is an array of functions (the exact number of them is unknown),
  3. all of them will return promise.
  4. Write a solution that all promises would be resolved sequentially
  5. without using async await
  6.  */
  7.  
  8. const fn1 = () => new Promise((resolve) => {
  9.   setTimeout(() => resolve(1), 1000);
  10. });
  11.  
  12. const fn2 = () => new Promise((resolve) => {
  13.   setTimeout(() => resolve(2), 1000);
  14. });
  15.  
  16. const fn3 = () => new Promise((resolve) => {
  17.   setTimeout(() => resolve(3), 1000);
  18. });
  19.  
  20.  
  21. // Iterable
  22. // function consistently(fns) {
  23. //   if(fns.length === 0) return Promise.resolve(0);
  24.  
  25. //   let stack = [fns[0]()]
  26.  
  27. //   for(let i = 1 ;i < fns.length; i++){
  28. //     const currFn = fns[i];
  29.  
  30. //     stack.push( stack[i-1]
  31. //         .then(r1 => currFn()
  32. //           .then(r2 => r1 + r2))
  33. //     )
  34. //   }
  35.  
  36. //   return stack[stack.length - 1]
  37. // }
  38.  
  39.  
  40. // Recursive
  41. function consistently(fns) {
  42.   if(fns.length === 0) return Promise.resolve(0);
  43.  
  44.   const [fn, ...otherFns] = fns
  45.  
  46.   return fn()
  47.       .then(res => consistently(otherFns)
  48.         .then(allRes => allRes + res))
  49. }
  50.  
  51.  
  52.  
  53. consistently([fn1, fn2, fn3]).then((sum) => console.log(sum));
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement