-1

I can use the following function to convert an API to an object and print it out:

function covertApiTobj(){
    fetch('https://api.chucknorris.io/jokes/random?category=dev')
      .then(res => res.json())
      .then(data => console.log(data));}

But how can I create another variable to let it equal to the object that has been converted from the API, something like this:

function covertApiTobj(){
    fetch('https://api.chucknorris.io/jokes/random?category=dev')
      .then(res => res.json())
      .then(data => console.log(data));
    
    const newdata = fetch('https://api.chucknorris.io/jokes/random?category=dev')
      .then(res => res.json())
 }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
William
  • 3,724
  • 9
  • 43
  • 76
  • 3
    what do you mean? – cmgchess Apr 24 '23 at 17:19
  • You can't do that. It's an asynchronous operation, so you are stuck with doing the work you want to do in your `.then()` callback. You can use `async` and `await` to make things *seem* like synchronous programming, but it still is not synchronous. – Pointy Apr 24 '23 at 17:20
  • You wanna fetch two API results, deserialize the returned JSON to JS objects and then compare them? It is very much unclear what you're asking for, I'm afraid. – Mushroomator Apr 24 '23 at 17:20
  • You're not "converting" the API, you're making a request to it. If you want the value from the response body, read https://stackoverflow.com/q/14220321/3001761. – jonrsharpe Apr 24 '23 at 17:20
  • 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) – imvain2 Apr 24 '23 at 17:20

2 Answers2

0

You can use promise chaining. Here is an example:

let apiUrl = 'https://api.chucknorris.io/jokes/random?category=dev';
let jsonData;

fetch(apiUrl)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    jsonData = data;
    console.log('JSON data saved:', jsonData);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });
Manuvo
  • 748
  • 5
  • 15
-1

You need to create Promise to pass a fetch response on a new variable and await the result in async function like this:

let getData = async() => {
  return fetch('https://api.chucknorris.io/jokes/random?category=dev')
  .then(res => res.json())
  .then(res => res)
  .catch(err => err);
}
(async () => {
  let data = await getData();
  let newdata = await getData();
  console.log('data:',data);
  console.log('newdata:',newdata);
})();
Jordy
  • 1,802
  • 2
  • 6
  • 25