1

I am trying to grab json data from a pastebin link and serve it as a popup in my electron app, but when trying to return a axios request data, it comes up undefined, also the console.log gets executed earlier than the .then for some reason, I think this has something to do with the request being async, but I haven't found a way to wait for the .then.

Code:

function grabPopup(fetchurl) {
  axios
    .get(fetchurl)
    .then(response => {
      // handle success
      //console.log(response.data);
      return response.data;
    })
    .catch(function(error) {
      // handle error
      console.log(error);
    });
}

console.log(grabPopup("https://pastebin.com/raw/0L1erTs1"));

The console output:

undefined
{ title: 'Test', message: 'Test2' }
pepijn de oude
  • 39
  • 1
  • 10
  • Read that, didn't help me out, but thanks for linking it! – pepijn de oude Sep 29 '18 at 12:38
  • How can that didn't help you, it's exactly your problem. Of course grabPopup doesn't return anything, first of all you're not doing: `return axios`, and even if you do, it will return a `Promise` not the result. The `console.log` will always be executed earlier that the `.then` because that's how asynchronous execution works. You should reread the other question, and learn how asynchronous function work in javascript. – Marcos Casagrande Sep 29 '18 at 12:46
  • I'm learning asynchrounous functions now which is the reason I'm doing this project, I've read the entire thing, tried different ways of resolving the issue and it didnt work, so either I don't understand the article correctly OR The answer isnt there. – pepijn de oude Sep 29 '18 at 12:53
  • 1
    `grabPopup` miss the `return` statement – Alejandro Sep 29 '18 at 13:44
  • 1
    *either I don't understand the article correctly OR The answer isnt there* - the former. – Estus Flask Sep 29 '18 at 13:45

1 Answers1

3

The problem with grabPopup is that it isn't expose underlying promise, it should be:

function grabPopup(fetchurl) {
  return axios.get(fetchurl)...
}

This is special case of this popular problem. There is no way to access the result synchronously because the function is asynchronous.

It should be:

grabPopup("https://pastebin.com/raw/0L1erTs1")).then(result => {
  console.log(result);
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Well, I've tried a few iterations of the code, for some reason this code still doesn't work, I now understand what was being said about the return statement but it will still return undefined, [link](https://pastebin.com/ngbcdEQZ) here is the complete code of my project I'm starting to think I have a bigger mistake in my code. Thanks a lot for the effort you put in though! Edit: I'm a complete idiot and fixed it, Thanks a lot for the articles and the effort again everyone! – pepijn de oude Sep 29 '18 at 14:15
  • You're welcome. Yes, your code seems ok in this regard. – Estus Flask Sep 29 '18 at 14:26