Challenge Description
Unsuccessful attempts at implementing a snippet that includes a recursive function with setTimeout and a promise. Recursion and setTimeout works, but the promise doesn’t seem to be resolving as here is no message output in the thenable configured in projectMGR().
Solution Attempts
Extensively review of execution context, the various methods of promise resolving , exercises on MDN and review of solutions on stack overflow have proven unsuccessful. Additionally, attempts have been made at wrapping the call to the recursive function in an async (as it is currently configured), also configuring the the promise directly in the GEC.
stack overflow References
Solution 1
Solution 2
Solution 3
Any comments or assistance greatly appreciated.
| Expected Output | Actual Output |
|---|---|
| 10 more to go… | 10 more to go… |
| 9 more to go… | 9 more to go… |
| 8 more to go… | 8 more to go… |
| 7 more to go… | 7 more to go… |
| 6 more to go… | 6 more to go… |
| 5 more to go… | 5 more to go… |
| 4 more to go… | 4 more to go.. |
| 3 more to go… | 3 more to go… |
| 2 more to go… | 2 more to go… |
| 1 more to go… | 1 more to go… |
| Finished just in time for Happy Hour!🍻. |
projectMGR();
const prom = [];
async function recursiveInterval(arr, n, ms = 1000) {
return new Promise((resolve) => {
setTimeout (() =>
{
if (n === 0) {
resolve(`Finished just in time for Happy Hour!🍻. `)
} else {
console.log(`${n} more to go...`);
recursiveInterval(arr, n - 1) - arr[n - 1];
};
},ms);
}
);
};
async function projectMGR() {
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = arr.length;
new Promise(() => {
recursiveInterval(arr, n)
.then((resolve) => console.log(resolve))
})
}
>Solution :
This works better. And also always remember to use functions or variables AFTER you have defined them.
async function recursiveInterval(arr, n, ms = 1000) {
if (n === 0) {
return 'Finished just in time for Happy Hour!🍻.';
} else {
console.log(`${n} more to go...`);
await new Promise(res => { setTimeout(res, ms); });
const t = await recursiveInterval(arr, n - 1);
return t;
}
};
async function projectMGR() {
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = arr.length;
await recursiveInterval(arr, n)
.then((resolve) => console.log(resolve))
}
projectMGR();