ghood
November 22, 2021, 8:44pm
1
I am attempting to get the current session in javascript. The issue I am running into is the Promise will not resolve unless I am debugging and use a breakpoint. Here is my code (NOTE: placing a breakpoint at “return values” causes the promise to populate the values object EVERY TIME. Without the breakpoint the object NEVER gets populated.)
function GetSession(authClient, i) {
var values = { userId: '', sessionId: ''};
authClient.session.get()
.then(result => {
values.userId = result.userId;
values.sessionId = result.id;
}).catch(err => alert(err));
return values;
}
Anyone have any ideas?
eugene
April 12, 2022, 10:11am
2
You need to read up on how Promises work in Javascript
Try https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
There’s two ways to get what you are looking for - first to to have the function return a Promise
function GetSession(authClient, i) {
return new Promise(
(cb, err) => {
var values = { userId: '', sessionId: ''};
authClient.session.get()
.then(result => {
values.userId = result.userId;
values.sessionId = result.id;
cb(values)
})
.catch(e => {
alert(e)
err(e)
});
}
)
}
Otherwise turn GetSession into an async function
async function GetSession(authClient, i) {
var values = { userId: '', sessionId: ''};
try{
let result = await authClient.session.get()
values.userId = result.userId;
values.sessionId = result.id;
return values;
}catch(err){
alert(err));
}
}