Home > Software engineering >  How to assign the output of a Fetch call to a variable (Javascript)
How to assign the output of a Fetch call to a variable (Javascript)

Time:11-11

I try to connect the output of a Fetch call to my page variable, but I just cannot seem to do it. Could you please check out the code underneath and help me out?

enter image description here

CodePudding user response:

You will have to make the surrounding function an async function, and then await the response.

async function(){
    try{
        var outputVariable = await fetch("URL").text();
        \\ Use outputVariable
    } catch(e){
        console.log('error', e);
    }
}

CodePudding user response:

Or you can use the axios instead of the fetch.

import axios from 'axios';

const response = await axios('https://api2.online');

console.log(response.data);

CodePudding user response:

I think the async/await approach will solve your issues.

async outputvariable() {
  try {

     const response = await fetch('https://api2.online-conve', {
         method: 'GET',
         credentials: 'same-origin'
     });
      const rlt = await response.json();
      return rlt;
  } catch (error) {
   console.error(error);
  }
}
  • Related