简体   繁体   English

在单个异步中链接等待 function

[英]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我的 IDE 状态

TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. TS1308:'await' 表达式只允许在异步函数和模块的顶层使用。

It currently cannot compile, I am trying to pass the token value into another axios API call.它目前无法编译,我正在尝试将令牌值传递给另一个 axios API 调用。 However this is currently not possible because of the error above.但是,由于上述错误,目前这是不可能的。 Any clue on how to fix this will be appreciated任何有关如何解决此问题的线索将不胜感激

await must be directly in an async function, you need to make the callback function async as well. await必须直接在async function 中,你也需要使回调 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 mentioned, there's no point to mix await and .then , your code could be like this:正如 Bergi 提到的,没有必要混合await.then ,您的代码可能是这样的:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM