What exactly is "anonymous" in the call stack from Chrome devtools? - devtools

Whenever I'm debugging in chrome, I mostly see anonymous included in the call stack, what exactly is that anonymous?

These are anonymous functions like:
() => { ... }
Methods without name.

Related

Is there a way to restrict which functions could be called through google.script.run?

I just deployed my first google apps script web app. However, I'm concerned about all the functions defined in the code.gs. They could be called by anyone with access to the dev console in chrome. They could call google.script.run on any of them.
Some of those functions are there only as a foundation to use in other functions (example below). Is there a way to restrict which functions could be called through google.script.run?
function openRentManagerDatabase (spreaSheetId) {
return SpreadsheetApp.openByIspreadsheetId);
}
Yes, you can do it.
add _after function name, that way it will become a private function and will become inaccessible for google.script.run.
It will look like this:-
function openRentManagerDatabase_(spreaSheetId) {
return SpreadsheetApp.openByIspreadsheetId);
}
Do note that making it private means you can't run it directly from appscript editor by selecting it.
So when you want to run it by calling it through another function, you have to use _ everytime, just like this openRentManagerDatabase_().
Reference:
Private functions

Where Isolate can be defined in Flutter? How to start a thread in Flutter?

I am a new in Flutter, so the question can be kind of obvious, but I can't find any answer on the Internet.
I have a Flutter application with some screens and I would say on the fifth screen I have a button, which should trigger some heavy computation work (converting thousands of images). On the same screen there is a progress bar and it is supposed to display the progress.
I am puzzled how to implement that technically. The triggering is happening obviously on onPressed of the button.
if I simply call a Future<void> function, then the UI is freezing completely for the time of processing, which is obviously is not desired behavior
if I put my function inside compute, on the first await I get exception
Unhandled Exception: Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. which puzzles me, because I call WidgetsFlutterBinding.ensureInitialized() before runApp(). Anyway this method is not working.
compute(computationFunction, 'argument');
// ...
static void computationFunction(String argument) async {
await firstStepFunction();
// ...
if I put my function into Isolate.spawn I get exception Unhandled Exception: Invalid argument(s): Isolate.spawn expects to be passed a static or top-level function which is also puzzling me. I tried to make the function static and moved the function to the top level of this fifth screen module. Nothing changed. Am I supposed to start the Isolate at the main function? In all beautiful examples it is done like that. Can't I start the Isolate in the middle by the button click.
Isolate.spawn(computationFunction, receivePort.sendPort);
// ...
void computationFunction(SendPort sendPort) async {
await firstStepFunction();
// ...
In Java I think a simple new Thread(...).start() will do the job.
But how to do it in Flutter?
Update:
In my experiments I've noticed, that neither Flutter Hot Restart nor Hot Reload are not working correctly with isolates. You need really to run again the whole app.
I managed to start Isolate.spawn all right if async/await keywords are removed. Off course the called function should have its synchronous version. So this does not work universally.
Isolate.spawn(computationFunction, receivePort.sendPort);
// ...
static void computationFunction(SendPort sendPort) { // async removed
firstStepFunctionSync(); // the function is replaced with its synchronous version
// ...
I've found package flutter_isolate which allows to run the async functions:
FlutterIsolate.spawn(computationFunction, argument);
// ...
void computationFunction(SendPort sendPort) async {
await firstStepFunction();
// ...
I will try to use flutter_isolate package in my prototype.
You should read https://dev.to/alphamikle/why-should-you-use-isolates-in-flutter-1k5o, and look at package:isolates.
The article contrasts using main thread, compute, Isolate proper, and the isolates package, with advantages and disadvantages of each. Best article I've seen in a long time.
Also keep in mind, Java threads are data-shared, leading to possible deadlocks. Dart isolates are share-nothing, using "ports" to carefully move data between isolates, and no need for locking!
Check out this plugin, which provides an easy way to work with isolates with a worker abstraction or using Parallel methods, and has well-explained documentation.
https://pub.dev/packages/easy_isolate
The use is simple as
void main() async {
final worker = Worker();
await worker.init(mainHandler, isolateHandler);
worker.sendMessage(null);
}
void mainHandler(dynamic data, SendPort isolateSendPort) {
isolateSendPort.send(null);
}
// Top-level function (or static)
void isolateHandler(dynamic data, SendPort mainSendPort, SendErrorFunction onSendError) {
mainSendPort.send(null);
}
Or using the Parallel methods
Future main() async {
await Parallel.foreach(['test'], writeFile);
}
// Top-level function (or static)
void writeFile(String name) {
File(Directory.systemTemp.path + '/$name').createSync();
}

Cant figure out what these errors happening on my webstore? Anyone help, posting the error content

enter image description here
No idea whats going with these errors code, i dont understand why is it saying anonymous and its giving me security concerns
Strictly speaking, those are warnings (not errors). Nothing is broken, but some things may be running sub-optimally. The alerts are noting that the code on your site is preloading a number of assets but not using them right away. This may indicate that your site is unnecessarily using priority resources to bring those resources in.
Beneath the warning message, you are seeing what is known as a "call stack" - it's the chain of functions that have been called to get to the point that resulted in that warning message. There are two kinds of functions in Javascript: named functions and anonymous functions.
Named functions are what you might normally think of as a function. You declare it with something like:
function doSomething(parameter){
// Some awesome code here
}
And later call it as:
doSomething(some_input);
However, in Javascript we can also create un-named, aka anonymous, functions in-line. This is often done for 'callback' functions, or functions that serve as a part B to the main function's part A, especially when part A does something asynchronously.
For example, if we want to fetch a file and then do something with it once it loads, we would make an asynchronous file call and then run our callback function once it loads. If we're using a library like jQuery as a helper to make that call, our code might look something like this:
function getPageAndDoStuff(url, callback){
jQuery.get(url, callback)
}
// We can declare a named function to do our stuff...
function justLogIt(html){
console.log(html);
}
getPageAndDoStuff('/cart', justLogIt);
Alternatively:
// We can just declare an inline anonymous function to do that
getPageAndDoStuff('/cart', function(html){
console.log(html);
})
The latter is a common design pattern for many types of tasks, but you'll note that the function we pass around doesn't have a name. When something happens and we look at the call stack to see the order of functions that have been called to get us to that point, what name would we print? Each unnamed function in our chain is simply called "(anonymous)"
Going back to your posted image, there is nothing in what you're showing that indicates a cause for serious concern. The script file 'rocket-loader' is possibly pre-loading a few assets that it doesn't need to, so you may be able to boost your site's performance by tweaking whatever parameters 'rocket-loader' uses to be more selective in what you are pre-loading.

Is it possible to have "thread" local variables in Node?

I would like to store a variable that is shared between all stack frames (top down) in a call chain. Much like ThreadLocal in Java or C#.
I have found https://github.com/othiym23/node-continuation-local-storage but it keeps loosing context for all my use cases and it seems that you have to patch the libraries you are using to make it local-storage-aware which is more or less impossible for our code base.
Are there really not any other options available in Node? Could domains, stacktraces or something like that be used to get a handle (id) to the current call chain. If this is possible I can write my own thread-local implementation.
Yes, it is possible. Thomas Watson has spoken about it at NodeConf Oslo 2016 in his Instrumenting Node.js in Production (alt.link).
It uses Node.js tracing - AsyncWrap (which should eventually become a well-established part of the public Node API). You can see an example in the open-source Opbeat Node agent or, perhaps even better, check out the talk slides and example code.
Now that more than a year has passed since I originally asked this question, it finally looks like we have a working solution in the form of Async Hooks in Node.js 8.
https://nodejs.org/api/async_hooks.html
The API is still experimental, but even then it looks like there is already a fork of Continuation-Local-Storage that uses this new API internally.
https://www.npmjs.com/package/cls-hooked
TLS is used in some places where ordinary, single-threaded programs would use global variables but where this would be inappropriate in multithreaded cases.
Since javascript does not have exposed threads, global variable is the simplest answer to your question, but using one is a bad practice.
You should instead use a closure: just wrap all your asynchronous calls into a function and define your variable there.
Functions and callbacks created within closure
(function() (
var visibleToAll=0;
functionWithCallback( params, function(err,result) {
visibleToAll++;
// ...
anotherFunctionWithCallback( params, function(err,result) {
visibleToAll++
// ...
});
});
functionReturningPromise(params).then(function(result) {
visibleToAll++;
// ...
}).then(function(result) {
visibleToAll++;
// ...
});
))();
Functions created outside of closure
Should you require your variable to be visible inside functions not defined within request scope, you can create a context object instead and pass it to functions:
(function c() (
var ctx = { visibleToAll: 0 };
functionWithCallback( params, ctx, function(err,result) {
ctx.visibleToAll++;
// ...
anotherFunctionWithCallback( params, ctx, function(err,result) {
ctx.visibleToAll++
// ...
});
});
functionReturningPromise(params,ctx).then(function(result) {
ctx.visibleToAll++;
// ...
}).then(function(result) {
ctx.visibleToAll++;
// ...
});
))();
Using approach above all of your functions called inside c() get reference to same ctx object, but different calls to c() have their own contexts. In typical use case, c() would be your request handler.
Binding context to this
You could bind your context object to this in called functions by invoking them via Function.prototype.call:
functionWithCallback.call(ctx, ...)
...creating new function instance with Function.prototype.bind:
var boundFunctionWithCallback = functionWithCallback.bind(ctx)
...or using promise utility function like bluebird's .bind
Promise.bind(ctx, functionReturningPromise(data) ).then( ... )
Any of these would make ctx available inside your function as this:
this.visibleToAll ++;
...however it has no real advantage over passing context around - your function still has to be aware of context passed via this, and you could accidentally pollute global object should you ever call function without context.

Perform GM_xmlhttpRequest() from eval

I have a little Greasemonkey script that communicates with a servlet on (my) server. The servlet is sending back JavaScript code, which I eval() in the onload handler of the GM_xmlhttpRequest.
So far, all is working fine. Now, I'd like to use send another GM_xmlhttpRequest from within that eval()ed code. and here I'm stuck. I do not see any error, but all GM_* functions appear not to be working from within the eval(responsetext).
If I hard code the GM_xmlhttpRequest in the onload handler (no eval()), it is working fine.
It is possible to work around this problem, you can call GM_* functions with setTimeout set to 0 from eval'ed code. Try something like:
function myFunction()
{
GMXmlHttpRequest(...)
}
eval('setTimeout(myFunction, 0)');
A better solution is to extend Function.prototype with a function called safeCall that does this for you. Whenever you have any eval'ed code that will call into GM_* functions you'll need to have safeCall somewhere in that call chain.
Greasemonkey (GM) is hosting the user script, which means that it can add functions and objects to the user script, when you call eval() the script runs unhosted (the vanilla JavaScript is running it) and you don't get the GM API inside of it.
There is another solution. I have the similar problem, I don't want to put all my logic in user script, because if I change them, user need to update them by themselves. So what I want to do is separating the main logic from loading logic, the main logic will be loaded at beginning by the user script and eval them.
So I made a function "sendRequest", which is a wrapper of GM_xmlhttpRequest(), I need it anyway, because the method, server url and onError callback are always same for my application, so I just put them into my "sendRequest" function to make the xmlhttprequest simple.
In the main logic javascript code, which is loaded from server, there is no greasemonkey function call at all. If I want to for example communicate with server, I will call sendRequest instead. It works.

Resources