【问题标题】:Javascript Async/await with axios resolve pending [duplicate]带有axios的Javascript异步/等待解决待处理[重复]
【发布时间】:2021-06-08 17:59:26
【问题描述】:

我有一个简单的问题。我尝试在网上找到解决方案,但每次尝试都失败了。 我有这个代码:

   const getSideBarMenu1 = async () => {
      let myArray = []
      await axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
        console.log('res1', res)
        myArray = res.data
      }).catch(err => console.log(err))
      console.log('myArray', myArray)
      return myArray
    }

当我像这样使用这个功能时:

 const useFunction = getSideBarMenu1()
    console.log('useFunction', useFunction)

控制台日志的结果是:

useFunction Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(100)

如何将 PromoseResult 保存在变量中? 谢谢大家!

【问题讨论】:

  • 这是因为getSideBarMenu1 是一个异步函数。所以你需要用await getSideBarMenu1()调用它
  • 意外的保留字“等待”是终端返回的内容。我正在为 VueJS 使用 vuexy 模板
  • 您可以使用.then()。一个 promise 只能在 async 函数中被 await 调用。所以你可以这样做getSideBarMenu1().then(res =&gt; console.log(res)).catch(err =&gt; console.log(err))

标签: javascript vue.js async-await


【解决方案1】:

您需要等待承诺完成,然后才能访问其结果:

const useFunction = await getSideBarMenu1()

【讨论】:

  • 终端给我语法错误:意外的保留字“等待”。 ——
【解决方案2】:

getSideBarMenu1async,它返回一个 Promise,这意味着你必须等待它。

const useFunction = await getSideBarMenu1();

你也可以使用.then()

【讨论】:

  • 我知道!但是如果我使用 await 我无法编译。终端给我语法错误:意外的保留字“等待”。
【解决方案3】:

也可以直接从getSideBarMenu1函数返回数据:

const getSideBarMenu1 = async () => {
  const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts')
  return data
}


const useFunction = await getSideBarMenu1()

【讨论】:

    【解决方案4】:

    你在这里忘记了一个小关键字。

    const useFunction = await getSideBarMenu1()
    console.log('useFunction', useFunction)
    

    文章来源:https://jasonwatmore.com/post/2020/04/30/vue-fetch-http-get-request-examples 视频来源:https://www.youtube.com/watch?v=NHfyF0B4y8E

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2021-11-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 2019-01-04
      相关资源
      最近更新 更多