EmberJs Promises - Now to make .map() or .forEach() asynchronous?

175 Views Asked by At

Here is my controller action:

saveArticle(article, blocks) {
  let self = this;

  return RSVP.all(article.get('blocks').invoke('destroyRecord')).then(function () {
      blocks.data.map(function (item) {
        let block = self.get('store').createRecord('block', {
          article: article,
          type: item.type,
          format: item.data.format,
          text: item.data.text,
        });
        block.save();
        article.get('blocks').pushObject(block);
        debug('Block added.');
      });
      //article.save();
  });
}

How can I perform article.save () right after all the blocks have been created? That is, I want to delete all current blocks, create new ones, and save the article only after all these actions have been executed. I appreciate any ideas!

1

There are 1 best solutions below

0
On

I solved this issue with this code:

saveArticle(article, blocks) {
  let self = this;

  return RSVP.all(article.get('blocks').invoke('destroyRecord')).then(function () {
    debug("Blocks deleted");
    let promises = blocks.data.map(function (item) {
      let block = self.get('store').createRecord('block', {
        article: article,
        type: item.type,
        format: item.data.format,
        text: item.data.text,
      });
      return block.save();
    });
    return RSVP.all(promises).then(function () {
      debug("Blocks saved");
      return article.save().then(function () {
        debug("Article saved");
      });
    });
  });
}