0

how do you return a recursive function when there's promise inside it, here's my code so far

loop = (i) => {
  new Promise((resolve) => {
      setTimeout(() => {
        resolve(i)
      }, 100)
    })
    .then((res) => {
      if (res <= 5) {
        return loop(res + 1)
      } else {
        return true
      }
    })
}
console.log(loop(0))

11
  • 3
    return new Promise(...)? Otherwise each recursive call isn't part of the same chain. Commented Jan 23, 2020 at 8:17
  • You need to return the promise, and then you need to call console.log() when you resolve the promise. Commented Jan 23, 2020 at 8:19
  • @jonrsharpe can you please, explain it more to me. if I return this function as promise, where do i put the recursion then ? Commented Jan 23, 2020 at 8:22
  • 1
    A better question would be "what is this function supposed to do?" As an academic question the main exercise is to return something (you need a return keyword for arrow functions that have a block body rather than just a one liner) but as a practical question, I'm not sure I understand why you'd ever use this. What's the real world use case? Commented Jan 23, 2020 at 8:24
  • @Mike'Pomax'Kamermans well sometimes you just meet a person as a good backend engineer, and sometimes not. Commented Jan 23, 2020 at 8:33

1 Answer 1

3

You need to return the promise. Then use .then() to wait for the promise to resolve, and call console.log() there.

loop = (i) => {
  return new Promise((resolve) => {
      setTimeout(() => {
        resolve(i)
      }, 100)
    })
    .then((res) => {
      if (res <= 5) {
        return loop(res + 1)
      } else {
        return true
      }
    })
}
loop(0).then(result => console.log(result));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.