【问题标题】:Deferred export in EcmaScript modules (JavaScript)EcmaScript 模块 (JavaScript) 中的延迟导出
【发布时间】:2019-08-23 04:02:11
【问题描述】:

是否可以在 EcmaScript 模块中执行延迟导出(例如在导入脚本中执行一些异步操作之后)?

function do_export() {
    export default class AsyncClass {
        constructor() {
            this.name = "Async Class";
        }
    }
}

setTimeout(do_export, 500);

【问题讨论】:

  • 您是希望导入此模块的模块等待导出设置,还是在计时器运行之前得到undefined
  • 我期待等待:import("./path/to/AsyncClass.js").then(...)

标签: javascript ecmascript-6 import module export


【解决方案1】:

不是这样,importexport 都应该一次性评估。以后永远不能调用导出。这样想:如果do_export 被第二次调用会发生什么?

不过import可以作为函数使用:

const promise = import("module-name");
const module_name = await promise;

这意味着您可以将模块的导入推迟到需要时。

如您所愿,延迟导出的另一种方法是返回 Promise,这就是 Promise 的用途:

export default new Promise((resolve) => {
  setTimeout(()=>{
    class AsyncClass {
      constructor() {
        this.name = "Async Class";
      }
    }
    resolve(AsyncClass);
  }, 500);
});

现在您可以立即导入模块,但必须等待程序中的值:

import AsyncClass from "./AsyncClass.js";


(async ()=>{
    const instance = new (await AsyncClass)();
    console.log(instance.name);
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2017-02-22
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多