Asynchronous Function Returning Promise {
As demonstrated in the provided code, asynchronous functions often return a Promise, which represents the eventually available value. However, when attempting to access its value immediately, the console logs "Promise {
Resolving Promise Values
To obtain the desired token value, you must chain a ".then" handler to your promise. This handler captures the resolved result, whether it's already available or still pending:
let AuthUser = (data) => { return google.login(data.username, data.password).then((token) => { return token; }); }; let userToken = AuthUser(data); userToken.then((result) => { console.log(result); // "Some User Token" });
Promise Resolution Details
Promises adhere to the Promises/A specification, which mandates a specific resolution procedure:
Understanding Promise Chaining
Each ".then" handler's resolved value becomes the next handler's input, enabling a chain of asynchronous operations. The following examples illustrate this behavior:
Value Return:
function initPromise() { return new Promise((res, rej) => { res("initResolve"); }); } initPromise() .then((result) => { console.log(result); // "initResolve" return "normalReturn"; }) .then((result) => { console.log(result); // "normalReturn" });
Chained Promise Return:
function initPromise() { return new Promise((res, rej) => { res("initResolve"); }); } initPromise() .then((result) => { console.log(result); // "initResolve" return new Promise((resolve, reject) => { setTimeout(() => { resolve("secondPromise"); }, 1000); }); }) .then((result) => { console.log(result); // "secondPromise" });
The above is the detailed content of Why Does My Asynchronous Function Return `Promise { }` Instead of a Value?. For more information, please follow other related articles on the PHP Chinese website!