1

I'm trying to do something like this:

const axios = require('axios');
function load() {
  const response = axios.get('https://...');
  return response.data;
}

I can't make my function async. I need it to be declared exactly this way and return the data loaded from the URL via GET request.

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • Is this for nodejs or for the browser? – t.niese Jun 12 '22 at 19:39
  • @t.niese it's for nodejs – yegor256 Jun 12 '22 at 19:40
  • Ok, and is there a particular reason why you can't make it asnyc? – t.niese Jun 12 '22 at 19:40
  • @t.niese because all of my other functions in the program are "sync". I don't want to use `await` just because of axios – yegor256 Jun 12 '22 at 19:41
  • 1
    @yegor256 you simply cant. – bill.gates Jun 12 '22 at 19:42
  • @bill.gates maybe there is some workaround, with a waiting loop? – yegor256 Jun 12 '22 at 19:43
  • 1
    @yegor256 well it does not work with a loop for 1 reason. If you use an loop, your main thread is blocked. When your promise resolves, it wont get executed because the loop is blocked – bill.gates Jun 12 '22 at 19:44
  • You don't make synchronous network requests with JavaScript, point. With axios or otherwise. Deal with the asynchrony. – Bergi Jun 12 '22 at 19:45
  • @bill.gates how functions like `execSync` and `spawnSync` work? – yegor256 Jun 12 '22 at 19:46
  • @yegor256 "*all of my other functions in the program are "sync".*" - you [shouldn't need to make *all* function asynchronous](https://stackoverflow.com/a/45448272/1048572) in a well-designed program. Make those `async` where necessary, it shouldn't be a big deal. If you need help with that, please post the code of your program. – Bergi Jun 12 '22 at 19:47
  • 1
    @yegor256 well isnt `exec` for running commands in a shell? maybe you could use it for an curl request – bill.gates Jun 12 '22 at 19:48
  • As you mention `spawnSync` you could spawn a child process with `spawnSync` do the request there and pass its result serialized to the parent process. But I really think this is a bad idea. That is completely against the concept of how nodejs is designed. – t.niese Jun 12 '22 at 19:49

2 Answers2

2

Well you can try using XMLhttprequest:

const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

function syncRequest(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);
  return xhr.responseText;
}

(() => {
  const res = syncRequest("https://api.github.com/users/octocat");
})();

It will block until it receives an response

You will need to install the XMLHttprequest package:

https://www.npmjs.com/package/xmlhttprequest

bill.gates
  • 14,145
  • 3
  • 19
  • 47
1

suggestion: using async await

const axios = require('axios');

async function load() {
  const response = await axios.get('https://...');
  ...
}
HENOK MILLION
  • 309
  • 1
  • 9