如何在多个函数中传递承诺结果?

发布于 2025-01-17 21:09:36 字数 1060 浏览 3 评论 0原文

我发现了很多有关 Promise 的问题和答案,但我无法完全理解如何将它们应用到我的情况中。我正在尝试使用纯 JavaScript 在另一个函数中使用承诺链的结果。

我将如何去做类似下面的事情?

我的预期结果是 生日祝福 祝你生日快乐

相反,我得到 生日祝福 [对象承诺]

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

I've found lots of questions and answers about promises, but I can't quite wrap my head around how to apply them to my situation. I'm trying to use the result of a promise chain in another function using plain Javascript.

How would I go about doing something like the below?

My expected results is
Birthday Greeting
Happy birthday to you

Instead, I get
Birthday Greeting
[object Promise]

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若水微香 2025-01-24 21:09:36

您的承诺有2个问题

,第一个问题是

resolve(result + "you");

您在Promise解决后不返回最终结果。

第二个问题是

[object Promise]

Promise对象只是等待结果的状态,但是您没有等待任何结果,所以这就是为什么它是印刷[object Promise]

我使用 async/等待 等待您的Promise> 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>

如果您不喜欢async/等待可以调用,然后等待结果

//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>

You have 2 problems with your Promise

The first problem is

resolve(result + "you");

You don't return your final result after Promise resolved

The second problem is

[object Promise]

Promise object is just the state of waiting for results, but you didn't wait for any results, so that's why it's printed [object Promise]

I use async/await for awaiting the final result from your 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>

If you don't like async/await you can call then for awaiting results

//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>

扮仙女 2025-01-24 21:09:36

承诺是代表未来值的对象,而不是值本身。要访问已解决的值,您必须使用其then()方法,该方法接受可用值时将被调用的回调函数。

由于func1()返回phrase()的承诺,因此您的func2()应该看起来像

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

:您的短语()函数。最后的然后()调用resolve()不存在。这是短语()重写为简短的:

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

A promise is an object that represents a future value, not the value itself. To access the resolved value, you must use its then() method which accepts a callback function that will be invoked when the value available.

Since func1() returns phrase()'s promise, your func2() should look like this:

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

There also seems to be an error in your phrase() function. The last then() calls resolve() which doesn't exist. Here's phrase() rewritten for brevity:

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")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文