0

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);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Reyno Aug 29 '22 at 09:55

1 Answers1

0

Try the below code,

import axios from "axios";

const response = await axios.get(url, {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
});

const result = JSON.parse(response);

console.log(result); // shows the result in JSON

Hope this answers your question.

Praneeth
  • 36
  • 2
  • Hello, thanks, it works. however I still had to work without axios, but I found a solution be making all my code async in a function. However it was helpfuk, thanks again ! – Dioxygen78 Aug 30 '22 at 10:00