jeudi 11 juillet 2019

How to iteratively save child records in Ember.js?

I want to save a parent record and multiple child records to an external REST API using Ember Data. The problem I have is that I'm not sure what the best way to handle this asynchronously.

My first attempt looked something like this:

let parent = this.store.createRecord('parent');
parent.set('name', 'Bob');
parent.set('children', []);
parent.save().then(()=>{
  for (i=0;i<8;i++) {
    let child = this.store.createRecord('child');
    child.set('name', 'Child' + i);
    child.set('parent', parent);
    child.save().then(()=>{
      parent.get('children').pushObject(child);
      if (i == 7) {parent.save()}
    }
  }
})

This successfully creates the parent and all children but fails to save the ids of all children in the parent's record. Not all child.save() promises have resolved by time parent.save() is called.

I understand that RSVP is a library that can be used to resolve this problem, but I can't find any examples of its usage that make sense in context to what I'm trying to do.

Can anyone outline how I can rework this to ensure all children have been saved before attempting to save the parent?




Aucun commentaire:

Enregistrer un commentaire