lavezzi1
@lavezzi1

Как улучшить код?

Подскажите пожалуйста как лучше можно переписать этот кусок?

async createItem() {
        let record;
        let success = false;
        this.isLoading= true;
        await this.$fetch(`/api/items/${this.params.id}/new/`, {
          method: 'POST',
          body: JSON.stringify(this.createItemBody),
        })
          .then(response => response.json())
          .then((response) => {
            item = response;
            success = true;
          })
          .catch((err) => {
            this.isLoading= false;
            window.console.log(err);
          });
        if (success) {
          await this.dispatch('fetchSecondItem', id);
          this.items.push(item);
          this.dispatch('notification', {
            type: 'success',
            message: 'Item was created.',
          });
          this.resetForm();
        }
        this.isLoading= false;
      },
  • Вопрос задан
  • 395 просмотров
Решения вопроса 1
vahe_2000
@vahe_2000
я не понимаю что вы делаете наверное работайте на redux или flux.вы можете использовать try/catch и await вместо then.может что то вроде этого .что поделать с let record.вы даже не использовали.из чего вы взяли item

.then((response) => {
            item = response;
            success = true;
          })


async createItem() {
    this.isLoading = true;

    try {
      let res = await this.$fetch(`/api/items/${this.params.id}/new/`, {
        method: "POST",
        body: JSON.stringify(this.createItemBody)
      });
      let json = await res.json();

      await this.dispatch("fetchSecondItem", id);
      this.items.push(json);
      this.dispatch("notification", {
        type: "success",
        message: "Item was created."
      });
      this.isLoading = true;
      this.resetForm();
    } catch (err) {
      this.isLoading = false;
      console.log(err);
    }
  }
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
17 апр. 2024, в 00:13
800 руб./за проект
17 апр. 2024, в 00:06
240000 руб./за проект
17 апр. 2024, в 00:02
1000 руб./за проект