3

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.

iAmOren
  • 2,760
  • 2
  • 11
  • 23
Emmanuel
  • 121
  • 2
  • 11
  • Assuming you have `var newMes;` declared outside that function, all you need to do is remove the `const`. The important question however is what you plan on doing with that variable, and even more importantly: *when*, given that `fetch` is async. –  Jul 09 '20 at 15:28
  • @ChrisG Thanks Chris, that's what I tried but when I try to console.log it I get undefined. Here's my code: let newMes function generateNewQuote() { fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random') .then(response => response.json()) .then(data => { newMes = data.message; }); } generateNewQuote() console.log(newMes); – Emmanuel Jul 09 '20 at 15:32
  • Yes, here's the explanation: https://jsfiddle.net/khrismuc/efdgyq6n/ –  Jul 09 '20 at 15:33
  • @ChrisG Thank you so much! I have actually spent a couple of hours trying to solve this out. THANK YOU! – Emmanuel Jul 09 '20 at 15:42
  • You're welcome :) –  Jul 09 '20 at 15:44
  • 1
    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) - – user2864740 Jul 09 '20 at 15:57
  • The valid / suitable ways to solve the general approach of accessing an async return value are in that linked question: assignment to a variable in an outer scope from the callback is generally *not valid* even if it may “appear to work” at times. If the issue is just not knowing about variable scoping rules.. – user2864740 Jul 09 '20 at 16:00

2 Answers2

1

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 );
        });
}
Krishan Kumar
  • 394
  • 4
  • 13
  • 1
    While this answers OP's question in the title, the true problem is the async nature of fetch here. OP has already tried what you suggest. –  Jul 09 '20 at 15:34
  • @ChrisG , I think there will be no issue with async. – Krishan Kumar Jul 09 '20 at 15:37
  • ...just look at OP's comment under their own question. That's the definition of an "issue with async". –  Jul 09 '20 at 15:38
0

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.

cerebrus6
  • 86
  • 8
  • 1
    This question is a duplicate of the infamous https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call anyway –  Jul 09 '20 at 16:04