简体   繁体   中英

Storing JSON from fetch() API Call in variable

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM