Just starting out with JS and currently working on a project involving retrieving data from an API using a JS Notebook.
I'm trying to create a function that can make API calls based on a given URL, and then execute that function twice. The objective is to extract JSON Data from the API calls and store them in variables (Alldocs1 and Alldocs2).
However, I'm having trouble storing the results of the function inside the variables. While I've encountered similar issues before, the main difference here is that the fetch() method is being called within the main function itself.
I'm able to retrieve the JSON from the CallAPI() function, but how do I go about saving the obtained JSON from the API calls into the two variables? Any advice would be greatly appreciated.
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);