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();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>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") }