如何在ckeditor插件同步中读取JSON文件
我需要为 CKEditor 5 创建一个自定义插件,它将读取 JSON 并在工具栏的下拉列表中显示数据。 我面临的问题是异步获取数据,在将列表设置到 Init 方法中的配置之前,该数据尚未完成。
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
});
}
在此代码中,items 始终为 null,因为配置定义是在获取完成之前运行的。 我无法将 config.define 放在 then 子句中,因为 init 方法将在它之前完成。
那么,如何强制 fetch 等待结果,或者更好地说如何同步而不是异步获取数据?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后,我通过在构造函数中添加异步函数来解决我的问题
Finally, I solve my problem by adding async function into my constructor