Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- There is an array of functions (the exact number of them is unknown),
- all of them will return promise.
- Write a solution that all promises would be resolved sequentially
- without using async await
- */
- const fn1 = () => new Promise((resolve) => {
- setTimeout(() => resolve(1), 1000);
- });
- const fn2 = () => new Promise((resolve) => {
- setTimeout(() => resolve(2), 1000);
- });
- const fn3 = () => new Promise((resolve) => {
- setTimeout(() => resolve(3), 1000);
- });
- // Iterable
- // function consistently(fns) {
- // if(fns.length === 0) return Promise.resolve(0);
- // let stack = [fns[0]()]
- // for(let i = 1 ;i < fns.length; i++){
- // const currFn = fns[i];
- // stack.push( stack[i-1]
- // .then(r1 => currFn()
- // .then(r2 => r1 + r2))
- // )
- // }
- // return stack[stack.length - 1]
- // }
- // Recursive
- function consistently(fns) {
- if(fns.length === 0) return Promise.resolve(0);
- const [fn, ...otherFns] = fns
- return fn()
- .then(res => consistently(otherFns)
- .then(allRes => allRes + res))
- }
- consistently([fn1, fn2, fn3]).then((sum) => console.log(sum));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement