'How to read json file in CKEditor plugin synchronous
I need to create a customs plugin for CKEditor 5 that will read a JSON and will show data in a dropdown list in the toolbar. the problem I faced is async fetching data which is not finished before setting the list into the configuration in the Init method.
export default class PlaceholderEditing extends Plugin {
static get requires() {
return [Widget];
}
init() {
this._defineSchema();
this._defineConverters();
this.editor.commands.add('placeholder', new PlaceholderCommand(this.editor));
this.editor.editing.mapper.on(
'viewToModelPosition',
viewToModelPositionOutsideModelElement(this.editor.model, viewElement => viewElement.hasClass('placeholder'))
);
var items=new Array();
fetch('/GetTerms').then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
}).then(data => {
items = data;
});
this.editor.config.define('placeholderConfig', {
types: items
});
}
in this code items always is null because config define is run before the fetch is finished. I couldn't put config.define in the then clause because init method will be finished before it.
So, how can I force fetch to wait for the result or better to say how can I fetch data sync not async?
Solution 1:[1]
Finally, I solve my problem by adding async function into my constructor
init() {
return (async () => {
this._defineSchema();
this._defineConverters();
this.editor.commands.add('placeholder', new PlaceholderCommand(this.editor));
this.editor.editing.mapper.on(
'viewToModelPosition',
viewToModelPositionOutsideModelElement(this.editor.model, viewElement => viewElement.hasClass('placeholder'))
);
var items = new Array();
await fetch('contractTerms.json').then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
}).then(data => {
console.log(data.items);
items = data.items;
});
console.log('pass');
this.editor.config.define('placeholderConfig', {
types: items
});
})();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mahdi Farhani |
