-1

I'm new to JavaScript and especially new to async functions. Anyway, I have an async JavaScript function that sends an axios GET request to my backend JSON DB on http://localhost:3000/user. Then, inside my non-async function, I'm calling the async function. However, despite the fact that the condition is true, it's returning false:

index.js

async function doOne() {
  await axios.get('http://localhost:3000/user/?name=Alan&id=17')
  .then((response) => {
    console.log(response.data);
  });
}

function test() {

var x = doOne().then(result => console.log(result));

  if (x === true) {
    console.log("There are users")
  } else {
    console.log("No users")
  }
} 

doOne()
test()

db.json

{
  "user": [
    {
      "id": 17,
      "name": "Alan",
      "profile": "https://shorturl.at/ltCNU",
      "team": "Ireland"
    },
    {
      "id": 18,
      "name": "Joe",
      "profile": "https://shorturl.at/ltCNU",
      "team": "England"
    },
    {
      "id": 19,
      "name": "Pinnochio",
      "profile": "https://shorturl.at/ltCNU",
      "team": "Wales"
    }
  ]
}

Output

Any assistance would be greatly appreciated.

  • I think your `test()` fn needs to be `async` and then your would need `var x = await doOne()...` similar to the [first example in the async/await documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) – mykaf Aug 23 '23 at 21:24
  • 1
    `doOne` doesn’t return anything, it just logs to the console. – deceze Aug 23 '23 at 21:28

0 Answers0