Node.js newbie: initialise an object with dynamic value, received by max-api addHandler?
Hello, absolute JS beginner here. I can not find a way to initialise an object with dynamic value, received by max-api addHandler. Here is what I have:
const maxAPI = require('max-api');
const Ableton = require('ableton'); // Parser for Ableton Live's .als format
var liveset = new Ableton('./test.als');maxAPI.addHandler('filepath', (alsPath) => {
//
});liveset.read(function(error, $) {
if (error) {
maxAPI.post(error);
}
else {
// parse liveset
}
}); This example works great until I try to initialise liveset var with a dynamic value of alsPath which is an output of live.drop.
How can one do this? Should the liveset.read logic be put inside the addHandler for the script to work? Thanks for help, I'm a little stuck by now.
Looks like if works like this:
const maxAPI = require('max-api');
const Ableton = require('ableton');
maxAPI.addHandler('filepath', (alsPath) => {
var liveset = new Ableton(alsPath);
liveset.read(function(error, $) {
if (error) {
maxAPI.post(error);
}
else {
// do something useful
}
});
});
Is this correct?
Yep, that's right. You are assigning to the `liveset` variable inside an event handler. In your first example, your `liveset.read` code was being executed immediately - before the event had fired. To make sure things are executed the right way round, you would make sure the code that relies on `liveset` to be initialised is run from inside the same callback. Just as you have it in your second example.
This is one of the main characteristics of modern JavaScript, especially as it is used in Node: asynchronous execution. If you want to wrap your head around it some more, read up on async, callbacks, and promises. :)
Yes, thank you! Doing some tutorials right now....