-1

i am trying to create a discord bot to display some informations about cryptocurrencies and there is the following error SyntaxError: await is only valid in async function, there is the part of the code that make me problems :

 const [coin, vsCurrency] = args;
      try {
        const { data } = await axios.get(
        `https://api.coingecko.com/api/v3/simple/price?ids=${coin}&vs_currencies=${vsCurrency}`
        );
Souf Bsslr
  • 13
  • 1
  • 2
  • 1
    The error is pretty clear: you can't use `await` except inside a function that starts with `async ...`, so if this code isn't even in a function: put it in a function, then call that function. And if it _is_ in a function, mark it as an asynchronous function using `async`. Alternatively, don't use `await` if you don't need auto-unpacking of a promise, just use the Promise you're given: `axios.get(...).then(...).catch(...)` – Mike 'Pomax' Kamermans May 05 '21 at 21:42
  • 1
    Does this answer your question? [await is only valid in async function](https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function) It's the first link doing a google search for your error, and the first link doing a search on stackoverflow. You should always do this before posting a question to SO – Jason Goemaat May 05 '21 at 21:53

1 Answers1

1

Rule number one: Read the error.

What it tells you is that you can use the await keyword only inside an async function. So your piece of code must be wrapped like this:

async function run() {

 const [coin, vsCurrency] = args;
 try {
   const { data } = await axios.get(`https://api.coingecko.com/api/v3/simple/priceids=${coin}&vs_currencies=${vsCurrency}`);
 } catch (err) {
   // Do something about the error.
 }
}

// Don't forget to run your function
run();

Read this for a better understanding of async/await.

geauser
  • 1,005
  • 8
  • 20
  • ok thank you very much, i tried this in the following way but my discord bot is still not working i don't know what to do – Souf Bsslr May 05 '21 at 21:53
  • @SoufBsslr make sure to accept my answer if it fits you, so your question does not appear anymore in the pending questions list. – geauser May 05 '21 at 21:54
  • If you have another problem @SoufBsslr ask another question! – geauser May 05 '21 at 21:57