Используйте asyn c вызов API внутри l oop в вычисляемом свойстве с vue -asyn c -computed - PullRequest
0 голосов
/ 17 апреля 2020

У меня есть вычисляемое свойство внутри Vue компонента, которое выглядит следующим образом:

allUsers() {
  const vm = this;
  const users = this.getAll.map((item) => {
    let newUser = {};
    if (typeof item !== 'object') {
      newUser = {
        id: vm.userModel.id,
        userId: vm.userModel.userId,
        data: null,
        tenantData: null,
      };
    } else {
      newUser = item;
    }
    return newUser;
  });
  return users;
},

Мне нужно вставить некоторые дополнительные данные в каждый newUser объект, но получение этих данных требует 1) зацикливания через другой набор данных для каждого элемента newUser и 2) получения данных, возвращаемых из вызова ax ios в конечную точку API REST:

async delete({ device, personId }) {
    return await super.perform(axios.delete(ServiceUrlProvider.gmiUrl()
      .concat('/person/')
      .concat(personId)
      .concat('/device/')
      .concat(device.deviceId)));
  }

В идеале я мог бы сделать что-то подобное :

allUsers() {
  const vm = this;
  const users = this.getAll.map((item) => {
    let newUser = {};
    if (typeof item !== 'object') {
      newUser = {
        id: vm.userModel.id,
        userId: vm.userModel.userId,
        data: null,
        tenantData: null,
      };
    } else {
      newUser = item;
    }
    this.tenantApps.forEach((app) => {
      userDeviceService.fetchPersonAppDevice({
        id: item.id,
        appCode: app.code,
      })
        .then((resp) => {
          // Code here to add returned value to newUser object.
        });
    });

    return newUser;
  });
  return users;
},

но так как плохая практика разрешать асин c действия в вычисляемых свойствах, я должен попробовать что-то еще. Основываясь на том, что я нашел, я пытаюсь vue -asyn c - вычислить , и я переместил свой метод в отдельный объект asyncComputed:

  asyncComputed: {
    allUsers() {
      const vm = this;
      const users = this.getAll.map((item) => {
        let newUser = {};
        if (typeof item !== 'object') {
          newUser = {
            id: vm.userModel.id,
            userId: vm.userModel.userId,
            data: null,
            tenantData: null,
          };
        } else {
          newUser = item;
        }

        this.tenantApps.forEach((app) => {
          userDeviceService.fetchPersonAppDevice({
            id: item.id,
            appCode: app.code,
          })
            .then((resp) => {
              if (Array.isArray(resp.data) && resp.data.length > 0) {
                newUser.hasDevice = true;
              } else {
                newUser.hasDevice = false;
              }
            });
        });

        return newUser;
      });
      return users;
    },
  },

Моя проблема заключается в том, чтобы allUsers() ожидал ответного вызова на userDeviceService.fetchPersonAppDevice(), поскольку, как и сейчас, он завершается и возвращается без ожидания. Я не могу просто использовать await на forEach l oop. Как мне реализовать этот вызов, чтобы я мог добавить возвращенные данные в мой newUser объект?

ОБНОВЛЕНИЕ: В комментариях Estus Flask ниже я изменил вычисленное значение allUsers следующим образом:

asyncComputed: {
  async allUsers() {
    const vm = this;
    const users = this.getAll.map((item) => {
      let newUser = {};
      if (typeof item !== 'object') {
        newUser = {
          id: vm.userModel.id,
          userId: vm.userModel.userId,
          data: null,
          tenantData: null,
        };
      } else {
        newUser = item;
      }
      const devicePromises = [];
        this.tenantApps.forEach((app) => {
          devicePromises.push(userDeviceService.fetchPersonAppDevice({
            id: item.id,
            appCode: app.code,
          }));
        });
        const devices = await Promise.all(devicePromises);
      return newUser;
    });
    return users;
  },
},

Однако я получаю ошибка при вызове await Promise.all(devicePromises); о том, что the await operator can only be used in an async function. Я изменил allUsers на асинхронный, так почему ошибка?

...