I'd like to convert this Ember route action to use ES2017 async / await. Can someone please explain what this would look like?
Per spec, I already added: babel: { includePolyfill: true }
to my ember-cli-build.js file:
save() {
let tenant = this.modelFor(this.routeName).tenant;
let app = this.modelFor(this.routeName).app;
return tenant.save().then(()=> {
return tenant.get('app').save({ adapterOptions: { tenantId: tenant.id }}).then(() => {
this.transitionTo('tenants.tenant.info', tenant.id);
}).catch((error) => {
tenant.get('app').rollback();
throw error;
});
}).catch((error) => {
tenant.rollback();
throw error;
});
}
Your code, converted to async/await:
async save() {
let tenant = this.modelFor(this.routeName).tenant;
let app = this.modelFor(this.routeName).app;
try {
await tenant.save();
try {
await tenant.get('app').save({ adapterOptions: { tenantId: tenant.id }});
this.transitionTo('tenants.tenant.info', tenant.id);
} catch (error) {
tenant.get('app').rollback();
throw error;
}
} catch (error) {
tenant.rollback();
throw error;
}
}
To convert from promises, you add the await
keyword to method calls that return promises. Everything that you place in the then
method of the promise you can simply put after the await
statement.
The promises' catch
methods convert to regular try/catch blocks.