Home >Web Front-end >JS Tutorial >Why Does My Async Function Return `Promise { }` Instead of the Expected Value?

Why Does My Async Function Return `Promise { }` Instead of the Expected Value?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 22:03:12960browse

Why Does My Async Function Return `Promise {  }` Instead of the Expected Value?

Why Does My Asynchronous Function Return Promise { <pending> } Instead of a Value?

Problem:

In the provided code:

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

When executing the following:

let userToken = AuthUser(data)
console.log(userToken)

The output is:

Promise { <pending> }

Explanation:

Promises in JavaScript are used to represent asynchronous operations. If an asynchronous function returns a promise that is still unresolved, it will log as "pending" when printed.

To capture the result of an asynchronous call, you must use the .then method on the promise. This method takes a callback function as an argument, which will be executed when the promise is resolved.

Solution:

To correctly log the token from the asynchronous function, modify the code as follows:

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

By using .then, you can handle the result of the promise regardless of whether it is resolved or still pending.

Details:

Promises only resolve once, and the resolved value is passed to .then or .catch methods. The Promises/A spec states that if the function in the .then handler returns a value, the promise resolves with that value. If the handler returns another promise, the original promise resolves with the resolved value of the chained promise.

The above is the detailed content of Why Does My Async Function Return `Promise { }` Instead of the Expected Value?. 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