Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
return final result from recursive function with promises

a have a little problem with recursive function that return promises:

function like this:

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("result");
    }, 500);

});

let count = 1;
const recursiveWithPromise = () => {
    return promise.then(result => {
        count += 1
        if (count !== 10) {
            return recursiveWithPromise();
        }
        if (count === 10) {
            return 'finalResult'
        }
    });
}

let a = recursiveWithPromise()

I want to save only finalResult in some variable, but if i save it like this:

const someVar = recursiveWithPromise(params) or const someVar = recursiveWithPromise(params).then(res => res) it was undefined. So how i can get my finalResult ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You are currently not returning the result of the recursive call. If you do, the last frame result will be returned back and forth to the first frame and will eventually get you the desired result:

return recursive(newParams);

Indeed, the return value of a Promise callback can either be a bare value, or a Promise which is automatically being unwrapped.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Avoid using global state, especially with asynchronous programs. Instead write functions that accept arguments and return values -

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms))
}

function count(n) {
  console.log(n)
  if (n >= 10)
    return "done"
  else
    return sleep(1000).then(_ => count(n + 1))
}

count(0).then(console.log, console.error)

0
1
2
...
9
10
done

The beauty of async/await is that your asynchronous programs can look/feel nearly identical to their synchronous counterparts -

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms))
}

async function count(n) {
  console.log(n)
  if (n >= 10) return "done"
  await sleep(1000)
  return count(n + 1)
}

count(0).then(console.log, console.error)

0
1
2
...
9
10
done

If your recursive function expects a promise as input, the program changes slightly -

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms))
}

function count(p) {
  return p.then(n => {
    console.log(n)
    if (n >= 10)
      return "done"
    else
      return count(sleep(1000).then(_ => n + 1))
  })
}

count(Promise.resolve(0)).then(console.log, console.error)

0
1
2
...
9
10
done

Again, using async and await improves the readability of the program significantly -

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms))
}

async function count(p) {
  const n = await p
  console.log(n)
  if (n >= 10) return "done"
  await sleep(1000)
  return count(n + 1)
}

count(Promise.resolve(0)).then(console.log, console.error)

0
1
2
...
9
10
done
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda