retejs / rete

JavaScript framework for visual programming
https://retejs.org
MIT License
10.17k stars 653 forks source link

Adding nodes dynamically - what is going on here? #667

Closed michealroberts closed 11 months ago

michealroberts commented 1 year ago

I have the following code:

sequences.forEach(async (sequence) => {
  const node = createNode(sequence.id, sequence.name, socket);
  await editor.addNode(node);
});

Which adds a sample of nodes from a given data array.

Then, when calling the following:

const sequenceNodes = editor.getNodes();
console.log(sequenceNodes) // []

I get an empty array.

I'm kind of confused by this behaviour, if I log inside the forEach loop, I see that the nodes are being added. Furthermore, the nodes are rendering correctly.

For reference, this is the createNode function:

function createNode(id: string, label: string, socket: ClassicPreset.Socket) {
  const node = new Node(id);

  node.label = label;

  node.addInput("port", new ClassicPreset.Input(socket));
  node.addOutput("port", new ClassicPreset.Output(socket));

  return node;
}

This for me feels like a scoping bug?

Could someone explain why this dynamic adding of nodes doesn't seem to work outside of different scopes?

Ni55aN commented 1 year ago

the issue here is the incorrect use of async operations:

const sequenceNodes = editor.getNodes() // is called before any editor.addNode in the forEach
console.log(sequenceNodes)

This should have await

sequences.forEach(async (sequence) => {

to

await Promise.all(sequences.map(async (sequence) => {
rete-js[bot] commented 11 months ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 10 days.