1

Line 20:19: Parsing error: Can not use keyword 'await' outside an async function

  18 | 
  19 |     try{
  20 |       const res = await axios.post('/upload', formData, {
     |                   ^
  21 |         headers:{
  22 |           'Content-Type':'multipart/form-data'
  23 |         }
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Massimo555
  • 11
  • 2
  • 1
    What is the function signature? You're showing some of the code but not the entire function. The error is saying that your function isn't async – rrd Feb 21 '20 at 11:41
  • Please post the entire function. Also I think the error is pretty self-explanatory. Just add `async` in front of your function declaration – Samuel Hulla Feb 21 '20 at 11:42
  • Does this answer your question? [await is only valid in async function](https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function) – Bergi Jul 31 '21 at 22:51

1 Answers1

3

You can't use directly await like this. You should create a function with async and then you can use await in function like that;

const myFunction = async () => {
  try {
    const res = await axios.get('bla')
  }
}
Ugurcan
  • 49
  • 8
  • const onSubmit = async => { e.preventDefault(); const formData = new FormData(); FormData.append("file", file); try { const res = axios.post("/upload", formData, { headers: { "Content-Type": "multipart/form-data" } }); const { filename, filePath } = res.data; setUploadedFile({ filename, filePath }); } catch (err) { if (err.response.status === 500) { console.log("there was a problem with the server"); } else { console.log(err.response.data.msg); } } }; – Massimo555 Feb 21 '20 at 11:57
  • @Massimo555 so, what is the problem? why you doesn't add await keyword before axios function? – Ugurcan Feb 21 '20 at 11:59
  • @Massimo555 I think the issue is the onSubmit function. Right now, your function is synchronous but has a parameter called async. By adding empty braces, you can change it to an async function which doesn't take any arguments: `const onSubmit = async => {` becomes `const onSubmit = async () => {`. Now you got yourself an async function that you can use `await` in. – Linschlager Feb 21 '20 at 12:05
  • i added await before the axios and its started throwing an error....that's what i want to debug and fix but i need help to do that – Massimo555 Feb 21 '20 at 12:07
  • thanks everyone the code is now working....i appreciate the help....no more errors – Massimo555 Feb 21 '20 at 12:20