I am making a POST REST API call and I guess I am missing something in the await. It's probably because I am new to the Javascript world. Below is my code :
var values = await sendNetworkRequest("",serverResponse);
logInfo(values);
And function sendNeworkRequest is the one which actually makes a API call :
async function sendNetworkRequest(text,cb) {
var xhr = new XMLHttpRequest();
xhr.open("POST",________);
xhr.setRequestHeader(_____);
var jsonData = JSON.stringify(________);
xhr.send(jsonData);
xhr.onload = function () {
var res = JSON.parse(xhr.responseText);
cb(res);
}
}
function serverResponse(data) {
console.log(data['ProviderIds']); // all good here
return data['ProviderIds'];
}
I successfully get the data in the variable 'data'. However, it is late by a few mili-seconds that the variable 'values' is not set. It remains undefined. I also tried only to find out the same behaviour.
sendNetworkRequest("",serverResponse).then(values => {
// values remains undefined
});
Can anybody help me to get return value in the variable 'values' ? Thanks in advance.
EDIT :
Following doesn't work too :
xhr.onload = await function () {
var res = JSON.parse(xhr.responseText);
// cb(res);
return res['ProviderIds'];
}