Home >Web Front-end >JS Tutorial >Why Do Asynchronous Functions Return Pending Promises Instead of Immediate Values?

Why Do Asynchronous Functions Return Pending Promises Instead of Immediate Values?

DDD
DDDOriginal
2024-12-13 19:20:11284browse

Why Do Asynchronous Functions Return Pending Promises Instead of Immediate Values?

Why does an asynchronous function return Promise with pending status instead of a value?

The code defines an asynchronous function, AuthUser, which invokes google.login() and returns the promise it yields. When the function is invoked, the promise is logged with pending status because its result has not yet been resolved.

Solution:

To access the promise's resolved value, it must be chained with .then() even if it's still pending. For instance:

AuthUser(data)
  .then((token) => {
    console.log(token); // "Some User token"
  });

Details:

Promises are one-way operations. Once resolved, their value is passed to the .then() or .catch() method regardless of their state (resolved or pending). The return value of .then() is the resolved value of the promise.

In the provided code, AuthUser returns the promise directly, making its resolved value unavailable until the .then() is invoked.

Additional Insights:

  • The Promises/A spec states that if the .then() handler returns a value, the promise resolves with that value. If it returns another promise, the original promise resolves with the resolved value of the chained promise.
  • Chained .then() handlers will always contain the resolved value of the chained promise returned in the preceding .then().
  • If the .then() handler returns a promise, the resolved value of that chained promise is passed to the following .then().

The above is the detailed content of Why Do Asynchronous Functions Return Pending Promises Instead of Immediate Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn