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

273
Vistas
¿Cómo transmito resultados prometedores en varias funciones?

He encontrado muchas preguntas y respuestas sobre las promesas, pero no puedo entender cómo aplicarlas a mi situación. Estoy tratando de usar el resultado de una cadena de promesas en otra función usando Javascript simple.

¿Cómo haría para hacer algo como lo siguiente?

Mis resultados esperados son Saludo de cumpleaños Feliz cumpleaños a ti

En su lugar, recibo un saludo de cumpleaños [promesa de objeto]

HTML

 <div id="Heading">Birthday</div> <p> <div id="Paragraph"></div>

JS

 //Create the phrase function phrase() { let p = new Promise((resolve, reject) => { setTimeout(() => { resolve("Happy "); }, 3 * 100); }); var q = (p.then((result) => { return result + "birthday " }).then((result) => { return result + "to "; }).then((result) => { resolve( result + "you"); }) ) return q; } //Add to the heading and return the phrase for use by another function function func1() { document.getElementById("Heading").innerHTML += "Greeting"; return phrase(); } //Insert the phrase into the DOM function func2() { document.getElementById("Paragraph").innerHTML = func1(); } //Invoke the whole bit func2();
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Tienes 2 problemas con tu Promesa

El primer problema es

 resolve(result + "you");

No devuelve su resultado final después de que se resolvió Promise

El segundo problema es

 [object Promise]

El objeto Promise es solo el estado de espera de resultados, pero no esperó ningún resultado, por eso está impreso [object Promise]

Uso async/await para esperar el resultado final de su Promise

 //Create the phrase async function phrase() { let p = new Promise((resolve, reject) => { setTimeout(() => { resolve("Happy "); }, 3 * 100); }); //wait for final result with `async/await` var q = await (p.then((result) => { return result + "birthday " }).then((result) => { return result + "to "; }).then((result) => { //need to return final result after Promise resolved return result + "you"; })) return q; } //Add to the heading and return the phrase for use by another function async function func1() { document.getElementById("Heading").innerHTML += "Greeting"; //wait for final result with `async/await` return await phrase(); } //Insert the phrase into the DOM async function func2() { //wait for final result with `async/await` document.getElementById("Paragraph").innerHTML = await func1(); } //Invoke the whole bit func2();
 <div id="Heading">Birthday</div> <div id="Paragraph"></div>

Si no le gusta async/await , puede llamar then esperar los resultados

 //Create the phrase function phrase() { let p = new Promise((resolve, reject) => { setTimeout(() => { resolve("Happy "); }, 3 * 100); }); var q = (p.then((result) => { return result + "birthday " }).then((result) => { return result + "to "; }).then((result) => { return result + "you"; })) return q; } //Add to the heading and return the phrase for use by another function async function func1() { document.getElementById("Heading").innerHTML += "Greeting"; return phrase(); } //Insert the phrase into the DOM async function func2() { func1().then(result => document.getElementById("Paragraph").innerHTML = result); } //Invoke the whole bit func2();
 <div id="Heading">Birthday</div> <div id="Paragraph"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Una promesa es un objeto que representa un valor futuro, no el valor en sí mismo . Para acceder al valor resuelto, debe usar su método then() que acepta una función de devolución de llamada que se invocará cuando el valor esté disponible.

Dado que func1() devuelve la promesa de phrase() , su func2() debería verse así:

 //Insert the phrase into the DOM function func2() { func1().then(greeting => { document.getElementById("Paragraph").innerHTML = greeting; }) }

También parece haber un error en su función de phrase() . El último then() llama a resolve() que no existe. Aquí está la phrase() reescrita por brevedad:

 function phrase() { let p = new Promise((resolve, reject) => { setTimeout(() => { resolve("Happy ")}, 3 * 100) }) return p.then(result => result + "birthday ") .then(result => result + "to ") .then(result => result + "you") }
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