简体   繁体   中英

How do I save the data I get from a fetch request in JavaScript into a variable that is external to my function

Obvsiouly I'm very new to Javascript. For an app that I'm building, I need to save the data I get from a fetch request into a variable that ideally I can access outside of my function. Any light on this would be hugely appreciated.

Here's my code:

function generateNewQuote() {
    fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
           .then(response => response.json())
           .then(data => {
            const newMes = data.message;
            console.log(newMes );
        });
}


I need to get the value of my newMes variable into a variable that I can specify in the global scope or alternative a way to access the newMes variable locate inside my generateNewQuote function in the Global Scope.

Change the variable Scope.

let newMes = [];
function generateNewQuote() {
    newMes = [];
    fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
           .then(response => response.json())
           .then(data => {
            newMes = data;
            console.log(newMes.message );
        });
}

This may not be the most right answer, but this works. As setTimeout also works somewhat like await outside an async function.

var newMes;
function generateNewQuote() {
fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
       .then(response => response.json())
       .then(data => {
        newMes = data.message;
        // console.log(newMes);
    });
}
generateNewQuote();
setTimeout(function() {console.log(newMes)}, 2000)

The code above basically waits for a while before putting newMes into the console. Because the problem of newMes being undefined is that the script is still fetching data from the server and thus requires a bit of time.

The problem of this is that 2000 milliseconds may not be enough to load the data and thus console.log(newMes) will return undefined.

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