我是 Javascript 的初学者,我正在构建一个应用程序来提高我的技能。在为该应用程序制作登录系统时,我在从“主”父函数返回所需数据时遇到问题。
这是具有 2 个“子”功能的主要功能:
mock.onPost('/api/account/login').reply((config) => {
// takes email and password from login form
const { email, password } = JSON.parse(config.data);
// create variables needed for user login
let login_response = '';
let memberId = '';
let firstName = '';
let lastName = '';
function loginProcess(email, memberId, firstName, lastName, login_response) {
if (login_response !== 'ok' ) {
return [400, { message: 'Please check your email and password' }];
}
// let's save the information returned by the backend in the user object
const db = {
user: {
id: memberId,
email: email,
firstName: firstName,
lastName: lastName
}
};
const { user } = db;
// create the accessToken using the User ID returned by the backend
const accessToken = jwt.sign(
{ id: user.id },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
// if everything is ok with the login, we return the user object and an acccessToken
return [200, { user, accessToken }];
}
// create the loginUser function that will make the request to the backend and database
async function loginUser(email, password, memberId, login_response, firstName, lastName) {
try {
// request to flask endpoint to check if user exist and returns user information
let loginResponse = await axios.get('http://localhost:5000/login/'+'?email='+email+'&password='+password)
login_response = loginResponse.data.response;
memberId = loginResponse.data.member_id;
firstName = loginResponse.data.name.firstName;
lastName = loginResponse.data.name.lastName;
// returns user information and login response
return loginProcess(email, memberId, firstName, lastName, login_response);
} catch (err) {
console.error(err);
}
}
// lets run the loginUser function
let res = loginUser(email, password, memberId, login_response, firstName, lastName);
});
基本上,该函数loginProcess
是在 async 函数中使用的函数loginUser
。两者都是 main 函数的子函数mock.onPost('/api/account/login').reply((config)
。
我需要主函数mock.onPost('/api/account/login').reply((config)
也返回子函数函数返回的值loginProcess
,不知道该怎么做。
我知道子函数是异步的,据我了解,主函数在异步完成运行之前完成“运行”并返回“空”值。但我无法弄清楚如何做到这一点。
我将不胜感激。如果我没有正确解释自己,请告诉我。