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

时间:2017-07-19 02:26:08

标签: 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

示例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
}

循环将在meta > next_page url上调用AXIOS GET,直到在结果中找到uuid或meta > next_page为空(意味着没有更多回复)。

2 个答案:

答案 0 :(得分:3)

如果您使用支持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()
  }
})

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

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++
      }
  }
})

Working example(至少在最新的Chrome中)。

答案 1 :(得分:3)

您应搜索的内容不是while loop,而是Recursion

<强>而

var counter = 10;
while(counter > 0) {
    console.log(counter--);
}

<强>递归

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

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

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

get();

如果你想把它与承诺联系在一起,那么你应该花一些时间自己搞清楚,每次只返回承诺;)