Await that's locked within a solo asynchronous function

async function submitForm(e){
  e.preventDefault()
  console.log(e.target)

  try {
    const response = await axios.post('/api/<PATH>', {username, password});
    console.log(response.data);
    const token = response.data.token

    if (token) {
      const json = jwt.decode(token) as { [key: string]: string};
  
      const secondResponse = await axios.post('/api/<PATH>', { token });
      const data = secondResponse.data;

An error is occurring on this particular line of code:

await axios.post('/api/<PATH>', { token })

My IDE is displaying the following message:

TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.

The current code cannot be compiled due to this issue. I am attempting to pass the token value into another axios API call, but it seems impossible because of the aforementioned error. Any suggestions on how to resolve this would be greatly appreciated.

Answer №1

await is required to be directly inside an async function; you should also make the callback function async.

async function submitForm(e){
  e.preventDefault()
  console.log(e.target)

  await axios.post('/api/<PATH>', {username, password})
    // async here
    .then(async res => {
      console.log(res.data)
      const token = res.data.token
      if (token){
        const json = jwt.decode(token) as { [key: string]: string}
  
        await axios.post('/api/<PATH>', { token })
          .then(res => {
            const data = res.data

As Bergi pointed out, it's not recommended to mix await and .then; your code can be structured like this:

async function submitForm(e){
  e.preventDefault()
  console.log(e.target)

  let res = await axios.post('/api/<PATH>', {username, password})
  console.log(res.data)
  const token = res.data.token
  if (token){
    const json = jwt.decode(token) as { [key: string]: string}
  
    res = await axios.post('/api/<PATH>', { token })
    const data = res.data;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Vue.js: "Trying to access properties of an object that is undefined (specifically '$refs')"

When we trigger methods from a parent component in a child component, we use the following code: await this.$refs.patientinputmask.$refs.patientpersonaldata.ChangePersonalData(); await this.$refs.patientinputmask.$refs.patientaddressdata.SavePersonalAddres ...

Return to the previous URL after executing window.open in the callback

I need help redirecting the callback URL back to the parent window that initially called window.open. Right now, the callback URL opens inside the child window created by the parent. Here's the scenario: The Parent Window opens a child window for aut ...

Prevent a JavaScript file from resetting when a user refreshes the page

I'm currently developing a desktop application using node.js and electron. My task involves creating a JavaScript file that manages multiple processes, stores them in a dictionary, and ensures that the dictionary content is retained even without any r ...

Using Phoenix Channels and Sockets in an Angular 2 application: A comprehensive guide

My backend is built with Elixir / Phoenix and my frontend is built with Angular 2 (Typescript, Brunch.io for building, ES6). I'm eager to start using Phoenix Channels but I'm struggling to integrate the Phoenix Javascript Client into my frontend. ...

Error: The jQuery TableSorter Plugin is unable to access property '1' as it is undefined

I've been attempting to utilize the jquery table sorter plugin, but I keep encountering an error when trying to sort the table. The error message I'm receiving is: cannot read property '1' of undefined This is the HTML code I have: ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

I am having trouble with my jQuery datatable Ajax call - instead of reaching the server, I am seeing an alert indicating

Looking for help with my web page. I have a table that needs to be populated using AJAX calls to the server-side method. I've implemented jQuery DataTables, and here's the code snippet: $(document).ready(function() { $("#tableUserList").DataTa ...

Using jQuery to adjust the length of a string to fit within a specific width

I am working with a table and need to input strings in each cell, but they are wider than the cell width. I want to shorten the strings without breaking lines, and add '...' at the end to show that the string is long. The table consists of aroun ...

Removing Click event upon button click - Implementing Vue and Vuetify

In my project using Vuetify, I have implemented a dialog that opens when a button is clicked. The dialog can be closed after completing the required actions. However, in the production environment, the dialog cannot be reopened more than once due to the re ...

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

Tips for avoiding page reloading with the use of vue, vue recaptcha, and axios

My experience with Vue and coding, in general, has gotten rusty. Currently, I'm tackling a small project that involves a form communicating with Python on the backend. While the backend part seems to be covered (knock on wood), the front end is giving ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...

How to handle a POST request with an empty body in Node.js express routing, utilizing body-parser

I'm facing an issue where my submission form's post requests are returning an empty body, regardless of the body parser settings I apply. All my dependencies in package.json are up to date, and a previous application I created (using the deprecat ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

Issue with .submit() not submitting form after setTimeout timer runs out

How can I add a delay after a user clicks submit on a form before it actually submits? I have an image that appears when the click event is triggered, but the form never actually submits... This is the HTML form in question: <form class='loginFor ...

"An error has occurred stating that the header is not defined in

It is a coding issue related to payment methods. The headers type is undefined in this scenario, and as a newcomer to typescript, pinpointing the exact error has been challenging. An error message is indicating an issue with the headers in the if conditio ...

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

Is it possible to navigate to the Next page using a different button instead of the pagination controls

Is it possible to navigate to the next page upon clicking a button labeled "Press me"? Here is the code snippet: <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/an ...

The sticky header is malfunctioning due to a null offsetTop value

import React , {useRef, useEffect} from 'react' import './header.css' const nav_links =[ { path:'#home', display:'Home' }, { path:'#about', display:'About& ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...