Hello,
I have a custom field I'm creating. Before the model is saved, I want to set the field value and ensure that it completes before validate returns. Setting the field value requires a 'thenable' function so it isn't synchronous.
To make sure it 'waits' on finishing, I overwrote the validate function for my custom field as shown below. I also overwrote the 'fetch' function which is where the actual 'thenable' bit is happening. I included that below as well.
Trouble is, I am always seeing 'invalid' when I attempt to save the record. If I remove 'async' and 'await' from the validate function it allows me to save the record but the custom field attributes are never set because it saves the record before this.fetch().then completes.... Can anyone advise?
I have a custom field I'm creating. Before the model is saved, I want to set the field value and ensure that it completes before validate returns. Setting the field value requires a 'thenable' function so it isn't synchronous.
To make sure it 'waits' on finishing, I overwrote the validate function for my custom field as shown below. I also overwrote the 'fetch' function which is where the actual 'thenable' bit is happening. I included that below as well.
Trouble is, I am always seeing 'invalid' when I attempt to save the record. If I remove 'async' and 'await' from the validate function it allows me to save the record but the custom field attributes are never set because it saves the record before this.fetch().then completes.... Can anyone advise?
Code:
/** * Validate field values. * * @return {boolean} True if not valid. */ validate: async function () { let valid = Dep.prototype.validate.call(this); await this.fetch().then( attributes => { this.model.set(attributes, {silent: true}); valid = false; } ).catch( (error) => { console.log(error); valid = true; } ); return valid; },
Code:
fetch: async function () { let data = Dep.prototype.fetch.call(this); await this.prepareMyFieldVal().then( object => { data[this.name] = object; } ).catch((error) => console.log(error)); return data; },
Comment