简体   繁体   中英

How to assign the output of a Fetch call to a variable (Javascript)

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

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

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

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

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