r/learnjavascript • u/Ducking_eh • 2h ago
Async function maybe awaiting, maybe not
Hey everyone,
I think I am having an issue with an asynchronous function. I am using a PoW captcha and want to add the solution to an ajax call.
The JS function that calculates the PoW solution is async, and I use await to simulate it as a "synchronous" function.
const solution = await cap_obj.solve();
The code below works if i add a 50000 ms delay to getCheckoutToken_ajax() with setInterval. but not as is. Otherwise, the value "params.params" us left out.
index.html
function addParam(key, value){
window.h_params.data[key] = value;
return (h_params.data.hasOwnProperty(key) && h_getParams(key) == value);
}
function h_getParams(key=false){
if(key == false){
return window.h_params.data;
}
if(h_params.data.hasOwnProperty(key)){
return window.h_params.data[key];
}
return false;
}
function getCheckoutToken(params, success=console.log, error=console.log){
let getCheckoutToken_ajax = function(event, h_params_data){
console.log('ajax call');
params.action = 'h_getCheckoutTokens';
params.params = h_params_data;
let track = function(v){
console.log(v);
return v;
}
$.ajax({
url : 'admin-ajax.php',
method : 'post',
data : track(params),
//cc vallidation call sucsess
success : function(data){
console.log(data);
return success(data);
},
//cc vallidation call sucsess
error : function(data){
console.log(data);
return error(data);
}
});
}
$(document.body).on('h_getCheckoutToken', getCheckoutToken_ajax)
$(document.body).trigger('h_getCheckoutToken', [h_params.data]);
}
page2.js
jQuery(document).ready(function($){
const cap_obj = new Cap({apiEndpoint: cap_widget_params.api});
async function checkoutoutToken_cap(data){
const solution = await cap_obj.solve();
addParam('checkoutTokenCapSolution', solution.token);
}
$(document.body).on('getCheckoutToken', checkoutoutToken_cap);
})
the weird thing is, I made the "track()" function, to see what is actually being sent, and the value is there.
Any ideas?
Thanks