Variables - Paultje52/background-tasks GitHub Wiki
JavaScript isn’t designed as a multi-threaded application. Background-tasks tries to solve this as good as possible, by using worker-threads, a native Node Module.
But variables are a little bit different. You can send variables to every worker. All these variables will be on vars.<variable>. variables is an alias of vars.
You can send every variable type that works with JSON.stringify!
But there are two catches!
When sending a variable, you’re sending the whole data, not just a reference. That means that if you change a variable in a worker, it isn’t changed in the main process or another worker. Variables are ment to be read-only!
Sending class instances is even more difficult! When sending a class instance, the data of the instance and the class code itself is needed. The class data gets converted to JSON and the code to a string. The worker will set the data to an object and set object.proto to the classes prototype code.
By doing this, all the functions of the class still work fine, but changing a variable in the class doesn’t change the instance on the main thread.
Sending classes really isn’t recommended, you should use background-tasks only for independent tasks.
Allright, now, let’s send a class. To do this, we have to send an object. The first property in the object needs to be _customClass, and the value of it needs to be true.
The second property is classVar. It needs to be the code of the class.
And the third, and last, property needs to be instance, and this can just be your class instance!
.sendVariable(“exampleClass”, {
_customClass: true,
classVar: someClass,
instance: someInstance
});With the execute functions, you’re sending a function. But all the variables that are declaired outside that function, aren’t available in the function. If you need to use packages, load them with require. If you need data, you can get it as a parameter or you need to request it yourself in the function.
If you’re using a callback in the function, you can return a promise and resolve it when you’re finished to get the data to the main thread!
Warning: You can only give parameters that are accepted by
JSON.stringify!
// Use request for an api call, then sort the data and return it to the main process.
let urlVariable = “some-url.com”; // We have the url in the mai process.
.executeNow(urlVariable, (url) => { // Send the variable and get the url as a parameter!
const request = require(“request”);
return new Promise((res) => {
request({
url: url,
json: true
}, (_err, _res, body) => {
// Body.array is very large
let array = body.array.sort();
res(array);
});
});
}).then((array) => {
// Do stuff with the array
});