异步函数间Promise获取问题:await调用getauthToken返回undefined但内部可打印正确值的解决方案
Hey, let's figure out why your authToken is coming back as undefined!
The Root Cause
Your getauthToken function is marked as async, but the problem is that the request.post inside it uses a callback-based pattern instead of returning a Promise. Even though you're using await when calling getauthToken, the function doesn't actually wait for the POST request to finish—it just returns the initial empty data string immediately. That's why console.log(authToken) prints undefined right away, while the body logs later once the request completes.
Fixes You Can Apply
We need to wrap the callback-based request in a Promise so await can properly wait for the request to resolve. Here are two straightforward ways to do this:
1. Manually Wrap the Request in a Promise
Rewrite getauthToken to return a Promise that resolves when the request succeeds, and rejects if there's an error:
async function getauthToken(username, password){ return new Promise((resolve, reject) => { request.post({ url:"http://35.232.47.147:8008/token", json: { username: username, password: password }, headers: { "Content-type":"application/json" } }, (err, { body }) => { if(err){ reject(err); // Pass the error to the caller return; } console.log(body); resolve(body); // Return the successful response body }); }); }
Now when you use await getauthToken(...), it will wait for the POST request to finish, and authToken will hold the actual response body instead of undefined.
2. Use a Promise-Aware Request Library
If you want cleaner code, switch to a library like request-promise (a Promise-based wrapper for request) or axios. Here's how it looks with request-promise:
First install the package:
npm install request-promise
Then update your function:
const rp = require('request-promise'); async function getauthToken(username, password){ const requestOptions = { url: "http://35.232.47.147:8008/token", method: 'POST', json: { username: username, password: password }, headers: { "Content-type":"application/json" } }; try { const body = await rp(requestOptions); console.log(body); return body; } catch (err) { throw err; } }
One Extra Thing to Check
In your authenticateWithLocalStrategy function, you're starting a database transaction with an async callback, but you don't wait for the transaction to finish before sending the response. This could lead to race conditions where the response is sent before the database updates (like userObject.update) complete. Make sure to await the transaction if your database library supports it:
// Add await here to wait for the transaction to finish await database().transaction(async function(transaction) { // ... your existing transaction logic ... });
内容的提问来源于stack exchange,提问作者Mathew Pius

