我可以使用for循环创建承诺数组吗?

时间:2019-08-11 22:52:21

标签: javascript vue.js promise axios

在我的Vue应用程序中,我使用了一个for循环来迭代字符串数组。 Axios将数组中的每个元素发送到API并接收调用的结果,我将该结果附加到数组中。不幸的是,响应并非总是以正确的顺序到达。有没有办法可以跟踪单个Axios请求,以便以后对响应进行解读?

编辑:根据下面goto1的评论,我已经开始使用Promise.all(),但收到错误消息。代码已更改以反映这一点。使用for循环会导致此错误吗?

这是我的代码:

var app = new Vue({
  el: "#app",
  data() {
    return {
      a: "",
      b: "Waiting...",
      word: "",
      array: [],
      promises: [],
      abc: []
    };
  },
  methods: {
    axi: function (p) {
      //create array of promises
      for (var x = 0; x < this.word.length; x++) {
        this.promises.push(axios.get("https://googledictionaryapi.eu-gb.mybluemix.net/?define=" + this.word[x]));

      }

      //promise.all
      Promise.all(this.promises)
    },

    //returns api call result for each item
    multi: function () {

      //this.a could be a string like “the quick brown fox”
      var word = this.a;

      //this.word turns into an array: ["the","quick","brown","fox"]
      this.word = word.match(/\b(\w+)\b/g);



      //each string is sent to the API
      this.axi().then((response) => {
          var r = response;

          //I am hoping to get something like [“the”, "quick", "brown", "fox"]

          console.log(r);

        })

        //ignore rest of code from here
        .catch(function (error) {
          console.log("Error! Could not reach the API. " + error);

        });




    },
    //handles other stuff
    getA: function () {
      if (this.a === "") {
        this.b = "Waiting...";
      }

      this.b = "Retrieving...";
      //for another thing
      this.array = [];
      this.abc = [];
      this.word = [];
      //function call
      this.multi();

    }
  }
});

0 个答案:

没有答案
相关问题