【问题标题】:How to access a variable modified in an async function present in one .js file in another .js file? [duplicate]如何访问在另一个 .js 文件中的一个 .js 文件中存在的异步函数中修改的变量? [复制]
【发布时间】:2020-06-17 15:43:50
【问题描述】:

我有两个文件 a.js 和 b.js。第一个运行一个异步函数,其中包含一个变量,每次修改时都会更改。我想在另一个 .js 文件中使用修改后的数据访问同一个变量

// a.js

var nodes; // I have defined a global variable
async function createEditor(container) {
    ...
    async function compile() {
        await engine.abort();
        await engine.process(editor.toJSON());
        nodes = engine.process(editor.toJSON());
    }
}

export {nodes};

第二个 .js 文件包含:-

// b.js

import {nodes} from './a.js';

console.log(nodes) // Outputs Undefined

【问题讨论】:

  • 在异步函数完成之前导出nodes 的值(并更改该值)

标签: javascript node.js reactjs scope


【解决方案1】:

为什么不颠倒逻辑呢? ?

在文件 A 上:

import { log } from './b.js';

var nodes; // I have defined a global variable
async function createEditor(container) {
    ...
    async function compile() {
        await engine.abort();
        await engine.process(editor.toJSON());
        nodes = engine.process(editor.toJSON());

        log(b);
    }
}

export {nodes};

在文件 B 中:

function log(...arguments) {
  console.log(...arguments);
}

export { log };

【讨论】:

  • 否则,在类似问题中建议使用这种带有 getter 和 setter 的观察者/订阅者模式:stackoverflow.com/a/37403125/2356080?
  • 感谢您的回复。我会检查那个:)
猜你喜欢
  • 2018-09-26
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
相关资源
最近更新 更多