Delete Multiple records

Hello:

I have a table with checkbox where user can select up to 20 records and delete all at once.

deleteSelectedUsers() { const selectedUsers = this.get(‘selectedUsers’); const userId = this.get(‘selectedUsers’).mapBy(‘id’);

  userId.forEach((item) => {
    this.get('ajax').request(`/api/v1/users/${item}`, {
      method: 'DELETE',
      data: { userId: item}
    }).then(() => {
      selectedUsers.forEach((d) => d.unloadRecord());
      selectedUsers.clear();
      this.set('confirmDelete', false);
      this.flashMessages.success('Users deleted');
    })
    .catch((err) => {
      console.log('err deleting User', err);
      this.flashMessages.danger('Failed to delete users');
    });
  });
},

This works fine, however it makes a call for each item selected in the table. Is there a way to wrap everything app and make one call to the server, therefore only generating one success message?

Try and wrap the ajax calls into one promise…

var promises = [];

userId.forEach((item) => {
  // Create new promise and add to array
  var promise = new Ember.RSVP.Promise(function(resolve, reject) {
    this.get('ajax').request(`/api/v1/users/${item}`, {
      method: 'DELETE',
      data: { userId: item },
      success: function() {
        resolve();
      },
      error: function(error) {
        reject(error);
      }
    });
  });
}

Ember.RSVP.Promise.all(promises).then(() => {
  selectedUsers.forEach((d) => d.unloadRecord());
  selectedUsers.clear();
  this.set('confirmDelete', false);
  this.flashMessages.success('Users deleted');
})
.catch((err) => {
  console.log('err deleting User', err);
  this.flashMessages.danger('Failed to delete users');
});