skip to Main Content

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())
 }

2

Answers


  1. 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);
      });
    
    Login or Signup to reply.
  2. 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 new Promise((resolve, reject) => {
        fetch('https://api.chucknorris.io/jokes/random?category=dev')
        .then(res => res.json())
        .then(res => resolve(res))
        .catch(err => reject(err));
      });
    }
    (async () => {
      let data = await getData();
      let newdata = await getData();
      console.log('data:',data);
      console.log('newdata:',newdata);
    })();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search