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!