【问题标题】:Passing axios.get URLs into axios.all based on options根据选项将 axios.get URL 传递给 axios.all
【发布时间】:2018-06-27 17:34:07
【问题描述】:

我正在构建一个 vue 应用程序,它将根据选择的选项搜索 YouTube 频道。

当该选项为true时,我将该字符串推入一个数组中,该数组包含axios.get()请求的URL。

我正在遍历该数组并运行 axios.get() 并返回值。我在 Promise{} 下收到响应,其中包含 [[PromiseValue]] 内的对象。

最后,我将响应组合成一个 vue 数据元素(catAndDogResults),但最后我得到了一个未定义的结果。

有没有更好的方法来做我想做的事情?

data () {
  return {
    catVideos: true,
    dogVideos: true,
    catResults: [],
    dogResults: [],
    catAndDogResults: []
  }
},
methods: 
  search: function() {
  var that = this
  var cats =  'https://www.googleapis.com/youtube/v3/search?part=snippet&q=cats'
  var dogs =  'https://www.googleapis.com/youtube/v3/search?part=snippet&q=dogs'
  var urls = []

  if (this.catVideos == true) {
    urls.push(cats)
  }

  if (this.dogVideos == true) {
    urls.push(dogs)
  }

  function getVideos() {
    for (var i = 0; i < urls.length; i++) {
      console.log(axios.get(urls[i])) // returns under [[PromiseValue]]:object
        return axios.get(urls[i])
    }
  }

  axios.all([
    getVideos()
  ])
  .then(axios.spread(function (catRes, dogRes) {
    that.catResults = catRes.data.items
    that.dogResults = dogRes.data.items
    that.catAndDogResults = that.catResults.concat(that.dogResults)
  }))
}

编辑

修正拼写错误

【问题讨论】:

  • 请不要忘记选择接受的答案。

标签: javascript arrays vue.js promise axios


【解决方案1】:

尝试更改您的 getVideos() 方法以在 for 循环之后返回数组:

function getVideos() {
    var requests = [];
    for (var i = 0; i < urls.length; i++) {
        requests.push(axios.get(urls[i]));
    }
    return requests;
}

然后,这样称呼它:

axios.all(getVideos())
     .then(function (catRes, dogRes) { ... })

【讨论】:

    【解决方案2】:

    @tiagodws 提供的答案应该可以解决这个问题。我只是想重写 getVideos 函数,你可以使用 ES6 语法编写它,如下所示:

    var getVideos = () =>  urls.map(url => axios.get(url))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-01
      • 2012-12-17
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多