0

So I'm building a Node.js app and I want to have a file where I do all the required http requests using Axios. Axios' requests return promises, with the http response in the "then" block. I want to export the response to my main file, but when I do that and log the result out, I get

Promise { <pending> }

The file where I do the requests:

const axios = require('axios');

exports.allCountries = () => {
  return axios
    .get('https://someapi.com')
    .then(response => {
      return response;
    })
    .catch(error => {
      console.log(error);
    });
};

My main file:

const fetch = require('./fetch'); // file with all requests
let countriesResponse = fetch.allCountries();

console.log(countriesResponse); // This logs Promise { <pending> } instead of the actual response
Robert Feduș
  • 311
  • 2
  • 16
  • 1
    @T.J.Crowder the module is exporting a function that returns a promise. OP is then trying to synchronously use the value (expecting the Promise to resolve before the console.log). I respectfully disagree with you. – Jared Smith Mar 27 '20 at 13:43
  • 1
    @JaredSmith - You're right, I thought they were trying to export the countries, but it's clearly a function. I simply misread it. Thanks! – T.J. Crowder Mar 27 '20 at 13:43
  • That's exactly what I want, @T.J.Crowder! – Robert Feduș Mar 27 '20 at 13:45
  • @RobertFedus - You want to export the countries, not a promise or a function? If so, that's a use case addressed by [top-level `await`](https://github.com/tc39/proposal-top-level-await), which is a Stage 3 proposal at the moment. It's implemented behind a flag in V8, which means it'll be in Node.js before too much longer. You'd have to switch to ESM module syntax, and then it would look like this: `export const allCountries = await axios.get('https://someapi.com');` Other modules would use it like this: `import { allCountries } from "./your-module";` Modules importing from your module... – T.J. Crowder Mar 27 '20 at 13:48
  • ...wouldn't run until the promise had settled (and won't run at all if the promise rejects). More in Chapter 19 of my book out in a couple of months (see my profile)... – T.J. Crowder Mar 27 '20 at 13:49
  • @T.J.Crowder exactly! That's the whole reason why I wanted to export in the first place, for cleaner code. But looks like cleaner is not really achievable in this. – Robert Feduș Mar 27 '20 at 13:50
  • @RobertFedus - Well, the top-level `await` version seems pretty clean (when you can do it). :-) – T.J. Crowder Mar 27 '20 at 14:48

0 Answers0