I'm new to JS and I am working on a JS Notebook to retrieve Data from an API.
I want to create a general function that calls an API via a given URL, then call that function twice. The goal is to retrieve the JSON Data from tha API and store it in to variables (Alldocs1 and Alldocs2).
However I can't get the result of the function to be stored inside the variables. I've seen similar problems but the difference is that here the main function itself calls fetch(). I manage to get the JSON but only from the CallAPI() function.
How can I store the JSON ovtained by the API calls inside the two variables ? Thanks
async function callAPI (url, data) {
var result=0;
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
}).then(function(response){return response.json();}).then(function(obj){console.log(obj);result=obj;}).catch(function(error){console.error("Something went wrong.");});
return result;
}
//--------------------------API CALLS-------------------------------------//
//AllDocs:
var res_json=0;
alldocs1 = callAPI("/api/allDocs/", {
"portal_type": [
"Quality Control Declaration"
]
}
)
alldocs2 = callAPI("/api/allDocs/", {
"portal_type": [
"Defect Declaration Operation"
],
"creation_date":"2022-08-22"
}
)
console.log(alldocs1); //RETURNS PROMISE NOT JSON
console.log(alldocs2);