Home > Web Front-end > JS Tutorial > Why Do Asynchronous Promises Initially Show a Pending State?

Why Do Asynchronous Promises Initially Show a Pending State?

Linda Hamilton
Release: 2024-12-12 11:11:09
Original
514 people have browsed it

Why Do Asynchronous Promises Initially Show a Pending State?

Why Asynchronous Promises Show Pending States Initially

Your code involves an asynchronous function using a promise, but when you try to access the token inside the promise, you're encountering a "Promise { }" instead of a resolved token.

Promise Resolution and Pending States

A promise represents an operation that may take time to complete, and it provides a way to handle the outcome of the operation either when it resolves (successful completion) or rejects (failure). Initially, a promise is in a pending state until its operation is completed.

Chaining Promises: Deferred Resolution

In your code, you return a promise from google.login. When you try to access the token immediately, the promise is still pending; it has not resolved yet. This means you'll receive the pending state as Promise { }.

Capturing Promise Results

To obtain the resolved value of a promise, you need to use its .then or .catch methods. These methods provide handlers that will execute when the promise either resolves or rejects, respectively. By chaining .then handlers, you can perform actions based on the resolved value of the promise.

Example: Capturing Promise Values

let AuthUser = function(data) {
  return google.login(data.username, data.password).then(token => { return token } )
}

let userToken = AuthUser(data)
console.log(userToken) // Promise { <pending> }

userToken.then(function(result) {
   console.log(result) // "Some User token"
})
Copy after login

In this example, we add a .then handler to the promise returned by AuthUser. The handler will execute when the promise resolves and will receive the resolved value as a parameter. The console.log statement inside the .then will then print the actual user token.

Conclusion

Promises offer a structured way to handle asynchronous operations. To access the resolved value of a promise, it's necessary to chain it with .then or .catch handlers. Only after the promise has resolved will the resolved value be available to your code.

The above is the detailed content of Why Do Asynchronous Promises Initially Show a Pending State?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template