help with Http Functions & Wix Backend

i am trying to call the backend function from the wix HTTP function module.
HTTP - function code

export function post_addToken(request) {
let headers = request.headers;
// console.log(headers);
// console.log(headers.token);
let token = headers.token;
let options = {
“headers” : {
“Content-Type” : “application/json”
}
};

if (token){
var tokenResponse = getTokenWithAPI(token).then((response) => {

  tokenResponse = JSON.parse(response); 
  console.log( "Json Token items " + tokenResponse.items[ 0 ].clientToken); 

return tokenResponse;
})

if (tokenResponse.items[ 0 ].clientToken){ // this is undefined
console.log( “Inside if” );
options.body = {
“items” : valid request
};
return ok(options);
}
} else {

options.body = { 

“error” : 404 Token Not Found
};
return notFound(options);
}

}

----my wix backend code—
export async function getTokenWithAPI(token){
// console.log(“inside fetch token value”+token);
let res = await fetch( URL ) ;
// console.log("raw res "+ res);
res = await res.text();
return res;
}

i want to return HTTP ok or not found options depending upon if the value from wix backend exists or not.

can anyone help me here?
tokenResponse value is undefined, and the same value I can access inside then function.
what am i missing here?

i will be exposing the HTTP function to 3rd party vendors.

You should read this documentation first:
https://www.wix.com/velo/reference/wix-http-functions

i did, that is how i manage to write the above code.
if you can guide or point out the issue, it would be of great help.

I guess you need to think async mode (promises)
The 1st if has a promise getTokenWithAPI and next "if you test the tokenResponse content.
The tokenResponse on 2nd “if” has no value .

One way… Chain another .then() to promise…

Should be:
getTokenWithAPI(…)
.then(… return tokenResponse)
.then(response => { 2nd “if” }))

Or

Insert the 2nd “if” in the first .then()

if (token){
var tokenResponse = getTokenWithAPI(token).then((response) => { tokenResponse = JSON.parse(response); console.log( "Json Token items " + tokenResponse.items[ 0 ].clientToken); return tokenResponse;
})

if (tokenResponse.items[ 0 ].clientToken){ // this is undefined console.log( “Inside if” ); options.body = { “items” : valid request };

return ok(options);

}

hi @mvveiga - i tried moving the first if inside the .then, technically it wont work. it says me body not found when i make the relevant request.

il chain another .then response and see update.

thanks

i was able to fix this, i had to return the query for it to work.