如何“同时循环” Axios GET调用直到满足条件?

ATL*_*ris 4 loops while-loop promise vue.js axios

我有一个API,可以返回一个留言板线程的答复列表(每个调用限制5个答复)。我正在尝试做的是在响应中查找特定的响应uuid。如果未找到,则对下5个答复进行另一个AXIOS GET调用。

我想继续此循环,直到调用UUID或AXIOS GET调用返回无结果为止。

示例API请求:

http://localhost:8080/api/v2/replies?type=thread&key=e96c7431-a001-4cf2-9998-4e177cde0ec3
Run Code Online (Sandbox Code Playgroud)

示例API响应:

"status": "success",
"data": [
    {
        "uuid": "0a6bc471-b12e-45fc-bc4b-323914b99cfa",
        "body": "This is a test 16.",
        "created_at": "2017-07-16T23:44:21+00:00"
    },
    {
        "uuid": "0a2d2061-0642-47eb-a0f2-ca6ce5e2ea03",
        "body": "This is a test 15.",
        "created_at": "2017-07-16T23:44:16+00:00"
    },
    {
        "uuid": "32eaa855-18b1-487c-b1e7-52965d59196b",
        "body": "This is a test 14.",
        "created_at": "2017-07-16T23:44:12+00:00"
    },
    {
        "uuid": "3476bc69-3078-4693-9681-08dcf46ca438",
        "body": "This is a test 13.",
        "created_at": "2017-07-16T23:43:26+00:00"
    },
    {
        "uuid": "a3175007-4be0-47d3-87d0-ecead1b65e3a",
        "body": "This is a test 12.",
        "created_at": "2017-07-16T23:43:21+00:00"
    }
],
"meta": {
    "limit": 5,
    "offset": 0,
    "next_offset": 5,
    "previous_offset": null,
    "next_page": "http://localhost:8080/api/v2/replies?_limit=5&_offset=5",
    "previous_page": null
}
Run Code Online (Sandbox Code Playgroud)

循环将在meta > next_pageURL 上调用AXIOS GET,直到在结果中找到uuid或meta > next_page为null(意味着不再答复)为止。

And*_*pov 8

您应该搜索的不是while loop,而是称为Recursion

同时

var counter = 10;
while(counter > 0) {
    console.log(counter--);
}
Run Code Online (Sandbox Code Playgroud)

递归

var countdown = function(value) {
    if (value > 0) {
        console.log(value);
        return countdown(value - 1);
    } else {
        return value;
    }
};
countdown(10);
Run Code Online (Sandbox Code Playgroud)

这意味着该函数会根据输出的特定标准不断调用自身。通过这种方式,您可以创建一个函数来处理响应并在值不适合您时再次调用自身(半代码):

function get() {
    axios.get('url').then(function(response) {
        if (response.does.not.fit.yours.needs) {
            get();
        } else {
            // all done, ready to go!
        }
    });
}

get();
Run Code Online (Sandbox Code Playgroud)

如果您希望它与承诺链接在一起,那么您应该花一些时间自己弄清楚,每次只返回一个承诺;)


Ber*_*ert 5

如果您要使用支持async / await的东西进行预编译,那么这是微不足道的。以下仅是示例。在您的情况下,您将检查guid或空响应。

new Vue({
  el:"#app",
  methods:{
    async getStuff(){
      let count = 0;
      while (count < 5){
        let data = await axios.get("https://httpbin.org/get")
        console.log(data)
        count++
      }
    }
  },
  mounted(){
    this.getStuff()
  }
})
Run Code Online (Sandbox Code Playgroud)

或者,根据您对我的评论的回复,

new Vue({
  el:"#app",
  async created(){
      let count = 0;
      while (count < 5){
        let data = await axios.get("https://httpbin.org/get")
        // check here for your guid/empty response
        console.log(data)
        count++
      }
  }
})
Run Code Online (Sandbox Code Playgroud)

工作示例(至少在最新的Chrome中)。