Paullo
Paullo

Reputation: 2127

Chained await within a single async function

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

  await axios.post('/api/<PATH>', {username, password})
    .then(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

The issue is on this line

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

My IDE states

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

It currently cannot compile, I am trying to pass the token value into another axios API call. However this is currently not possible because of the error above. Any clue on how to fix this will be appreciated

Upvotes: 0

Views: 206

Answers (1)

Hao Wu
Hao Wu

Reputation: 20885

await must be directly in an async function, you need to make the callback function async as well.

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 mentioned, there's no point to mix await and .then, your code could be 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;

Upvotes: 2

Related Questions