【问题标题】:Linking two event functions together synchronously将两个事件函数同步链接在一起
【发布时间】:2020-03-08 20:34:10
【问题描述】:

我有几个要听的事件。第二个事件html.set 中的函数取决于第一个事件initialised 中的函数先完成。我想出了一个使用承诺的解决方案,但感觉很脏。我想知道这是否是最好的方法?

var applyGoogleFonts = new Promise(function(resolve, reject) {
  editor.events.on('initialized', function() {
    _applyGoogleFonts().then(resolve);
  });
});

editor.events.on('html.set', function() {
  applyGoogleFonts.then(_setThemeFonts);
});

我应该补充一点,_setThemeFonts 取决于 html.set 的触发器首先完成之前的代码。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    不确定您是否会找到这种清洁剂,但只是建议一种替代方法:

    const waitForInit = new Promise(resolve => editor.events.on('initialized', resolve));
    const waitForHtml = new Promise(resolve => editor.events.on('html.set', resolve));
    
    waitForInit.then(_applyGoogleFonts).then(() => waitForHtml).then(_setThemeFonts);
    

    在等待第一个事件之前订阅这两个事件很重要,否则第二个事件可能会在添加第二个订阅之前触发。您的代码也能正确执行此操作。

    【讨论】:

    • 很好的答案 :) 它使逻辑更加明确。
    • 我发现我必须使用waitForInitialized.then(_applyGoogleFonts).then(function() { return waitForHtmlSet }).then(_setThemeFonts); 才能在html.set 之后设置主题字体。
    • 你说得对,.then() 不接受承诺作为参数。我已经确定了答案。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2011-03-28
    • 1970-01-01
    • 2021-10-14
    • 2016-05-24
    相关资源
    最近更新 更多