【问题标题】:Axios GET requests return empty promises to htmlaxios GET 请求返回空的 promise 到 html
【发布时间】:2021-11-22 18:25:23
【问题描述】:

我整天都在努力让这个工作,但我不知道发生了什么。

我有这个使用 vue v-for 的 html 表(我减少了代码以使其更清晰):

<table id="timeSheet-datatable" class="table table-striped dt-responsive w-100">
<thead>
    <tr>
        <th>Project</th>
    </tr>
</thead>
<tbody>
    <tr v-for="(timeSheet,index) in timeSheetListPageable">
        <td>{{getProjectById(timeSheet.projectId)}}</td>
    </tr>                                                   
</tbody>

我有这个js:

async getProjectByIds(param){

   var result = '';
   await axios
       .get(`/project/${param}`).then(response => {
             result= response.data.name;
         }, response => {
             (err) => console.log(err)
         });
   return await result;
},


getProjectById(param){

   const data = this.getProjectByIds(param);

   console.log(data)
   return data;

},

问题是我不知道为什么返回不起作用,表结果是空格,如果我在getProjectById方法中添加async和await返回是[object Promise]

getProjectByIdworks 属性内的console.log,它显示了来自 Axios 的正确返回,但返回表不起作用。我已经尝试在此代码中更改很多内容,有什么建议吗?

【问题讨论】:

  • awaited 函数上没有 then。你需要做var result = await axios.get(...)
  • 感谢您的回答。啊,好吧,但是 axios 会怎么样呢?我试着去做,但回报是[object Promise]
  • 不要从模板调用 getProjectById。数据应该在挂载的钩子中检索。

标签: javascript html vue.js async-await


【解决方案1】:

await resultaxios.then() 构造之后不会产生预期的顺序流。

您需要使用 Promise 或多个 await 语句来使代码可读并正确执行。

async getProjectByIds(param){

    var result = '';
    try {
        var response = await axios.get(`/project/${param}`)
        result = response.data.name;
    } catch (err) {
        console.error(err)
    }
    return result;
},


async getProjectById(param){

    const data = await this.getProjectByIds(param);

    console.log(data)
    return data;

},

我不确定实际的 response.data 声明。你可能需要也可能不需要在那里使用await

【讨论】:

  • 感谢您的回答!我刚刚尝试使用您的代码,console.log 正确显示了值,但前端返回到 html 表显示[object Promise]
  • 你必须看看如何在 vue 中加载 async 组件。参考:vuejs.org/v2/guide/components-dynamic-async.html
  • “构造不会导致预期的顺序流” - 它会。代码很丑陋,但这不是它不能按预期工作的原因。
猜你喜欢
  • 2021-02-03
  • 2022-01-01
  • 2019-05-31
  • 2021-08-08
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多