【问题标题】:Getting the right data but not where I expect it to be获得正确的数据,但不是我期望的数据
【发布时间】:2016-07-31 05:45:33
【问题描述】:

我的代码正在运行。但我很确定有一种更简单的方法可以做到这一点。现在的方式,我可以通过访问我的 Promise 中的 '_v' 键来获得我需要的结果。这就是为什么我认为我做错了什么。代码如下:

file1.js

import * as Utils from '../js/utils';

albumsArray() {
    this.albums = Utils.getAlbums(this.user, this.token);
}

utils.js

export async function getAlbums(user, token){
  let store = []
  let data = await axios.get(`https://api.imgur.com/3/account/${user}/albums/`, {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: 'application/json'
    }
  })
  .then(response => {
    response.data.data.map( data => store.push(data))
  })

  return store || [];
}

所以,按照现在的方式,我在相册['_v'] 中得到了我想要的结果。

Obs: albums(this.albums) 是我记录它时的一个承诺,而 _v 是我需要的数据的关键所在。我做错了什么。如何让我的代码看起来更好?

谢谢

【问题讨论】:

  • 在顶层你总是需要处理一个承诺。

标签: javascript asynchronous promise async-await ecmascript-next


【解决方案1】:

关于 async/await 很酷的一点是你得到的是实际值而不是承诺......你可以这样做:

export async function getAlbums(user, token){
  let response = await axios.get(`https://api.imgur.com/3/account/${user}/albums/`, {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: 'application/json'
    }
  })
  return response.data.data || [];
}

您正在将 response.data.data 中的所有内容推送到存储中...为什么不返回 response.data.data 本身?

那么 file1.js 也应该使用 async/await 这样你就可以得到数组而不是 promise...

async albumsArray() {
    this.albums = await Utils.getAlbums(this.user, this.token);
}

有道理吗?

【讨论】:

  • 很好的答案。我只是在文件 1 中移动了 response.data.data,并添加了一个 try and catch 来处理错误:try{ let store = await Utils.getAlbums(this.user, this.token); this.albums = store.data.data.map(data => Album.fromJson(this, data)); } 捕捉(错误) { (...) }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 2021-06-15
  • 2015-08-26
  • 2018-02-19
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
相关资源
最近更新 更多