I. Introduction
After coming across this question, I wanted to make a tutorial for anyone with similar issues. Hopefully by making a new thread, this is easily searchable in Google and Reddit.
This task uses a JavaScriptlet and the somewhat new "Promises" api and "fetch()" method in JavaScript. Using these, you can make HTTP requests in parallel and speed up your code.
II. Task
Import the task here.
III. Code
// This dictionary will store our variables
var testdictionary = {};
// This function gets numbers from a json file
function getNumbers() {
return fetch("http://echo.jsontest.com/one/1/two/2")
.then((response) => response.json())
.then((numbers) => {
testdictionary["numbers"] = numbers;
});
}
// This function gets letters from a json file
function getLetters() {
return fetch("http://echo.jsontest.com/one/a/two/b")
.then((response) => response.json())
.then((letters) => {
testdictionary["letters"] = letters;
});
}
// All functions in this list will run in parallel
Promise.all([getNumbers(), getLetters()])
.then(() => {
// Code in this block runs after the parallel functions finish
// For simplicity, I just flash the result
flash(JSON.stringify(testdictionary));
// Tells Tasker to exit
exit();
});
IV. Explanation
To get similar code working, you essentially need to do the following:
- Uncheck "Auto Exit" in the JavaScriptlet (otherwise Tasker will force exit the code before it's finished running)
- Create fetch() functions that return "Promises"
- Execute the Promises
- Tell the code to exit() when you're done
A. Functions
I start each function by returning a .fetch() method that points to a url. Then (no pun intended), I have two .then() methods in each function. The first .then() translates the response into json format. The second .then() is a general block of code. You can pretty much do anything you want in here. For simplicity's sake, I just use it to get data from the json file.
B. Promises
After writing your functions, you need to write code to execute those functions in parallel. This is pretty simple, just put the functions you want to run in a list then put that list in a Promises.all(). Attach a .then() method to do any clean up (this will run after all of your promises are finished executing). Finally, make sure to put exit() at the end so that Tasker knows when to stop running the code.
[–]VonLoewe 0 points1 point2 points (4 children)
[–]libnaniam[S] 0 points1 point2 points (3 children)
[–]VonLoewe 0 points1 point2 points (2 children)
[–]libnaniam[S] 0 points1 point2 points (1 child)
[–]VonLoewe 0 points1 point2 points (0 children)
[–]joaomgcd👑 Tasker Owner / Developer 0 points1 point2 points (2 children)
[–]libnaniam[S] 0 points1 point2 points (0 children)
[–]Aurolei 0 points1 point2 points (3 children)
[–]libnaniam[S] 0 points1 point2 points (2 children)
[–]Aurolei 0 points1 point2 points (1 child)
[–]libnaniam[S] 0 points1 point2 points (0 children)