Home > OS >  VueJS How to wait for axios data before continuing
VueJS How to wait for axios data before continuing

Time:11-15

I have this code, that should parse data into variable and then send a post request.

The problem is, I need one property from API and I don't know how can I wait before it's returned.

addFieldData(data, generatorData) {
      this.populateModel(data);

      console.log(this.model);

      this.$axios.post('data/webform/fields', this.model)
        .then(res => {
          console.log(res);

          this.$notify({
            group: "app",
            title: this.$t("general.success"),
            text: this.$t("general.action_has_been_processed"),
            type: "info"
          });
        }).catch(error => {
            this.$notify({
                group: "app",
                title: this.$t("general.error"),
                text: this.$t("general.error_occured"),
                type: "error"
            });
          console.log(error);
      });
    },
    populateModel(data) {
      this.model.label = data.label ?? {};
      this.model.hint = data.placeholder ?? {};
      this.model.attributes = data.attributes ?? {};
      this.model.maxlength = data.maxlength ?? 0;
      this.model.position = this.getFieldPosition();
      this.model.required = data.required ?? true;
      this.model.visible = data.visible ?? true;
      this.model.disabled = data.disabled ?? false;
      this.model.style_classes = data.style_classes ?? "";
      this.model.model = data.model ?? "";
      this.model.default = data.default ?? "";
      this.model.input_type = data.input_type ?? "";
      this.model.hint = data.hint ?? "";
      this.model.help = data.help ?? "";
      this.model.type = data.type;
    },
    async getFieldPosition() {
      const res = await this.$axios.get('/data/webform/'   this.idWebform   '/itemsCount');
      this.model.position = res.data.data.count   1;
      return res.data.data.count;
    },

In the addFieldData I call populateModel which should get position from API, but the post request is called before the getFieldPosition returns the data.

I'd like to try wait for the getFieldPosition first and then send the post request.

CodePudding user response:

First off, you should have everything with async/await without any .then.
Don't mix both of them. Use the first one.

Then, in your async populateModel method, you should have a

this.model.position = await this.getFieldPosition()

since getFieldPosition is async.

  • Related