I am learning ES6 Proxy, and try to understand param 'receiver' in a get trap, so I tried to console.log the receiver value. But when run in nodeJS, it causes an error:
RangeError: Maximum call stack size exceeded
let proxy = new Proxy({}, {
get (target, key, receiver) {
console.log('receiver:', receiver)
}
})
let obj = Object.create(proxy)
console.log(obj)
I want to know what is causing this error, and how to test receiver's reference in different situations.
The receiver in get (target, key, receiver) refers to the Proxy object, so you create an endless loop.
console.log(obj) tries to log the contents of obj, so it is iterating over all its keys, and retrieves their value. To get their value, the get of the Proxy is invoked, and in that get you have console.log('receiver:', receiver), and there receiver refers to obj, so again it tries to log the contents of obj, … which results in an endless recursive loop.
If you want to understand the param receiver in a get trap then you should not use logging, but the debugger, breakpoints, and the variable inspector in the debugger.
I hope that the following code will help to solve your problem.
let proxy = new Proxy({}, {
get: function (target, key, receiver) {
console.log('receiver:' + receiver);
}
});
let obj = Object.create(proxy);
console.log(obj);
Here you have create a Proxy object and it makes an infinite loop which never ends.
This error (maximum call stack trace exceed) means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. This is almost always because of a recursive function with a base case that isn't being met.
+(string concatenation operator) with object will call the toString method on the object and a string will be returned. So, '' + object is equivalent to object.toString(). And toString on object returns "[object Object]".
With , the object is passed as separate argument to the log method. So, this takes much time to provide arguments to the console log by sepertely and makes a "maximum call stack trace exceed" error.
So according to me I hope that this shold be the issue.
Related
I'm new to C++ and am working on an existing codebase, and am trying to figure out how to pass an r-value ref unique pointer into a lambda and transfer ownership properly.
Currently, we have:
void MyClass::onResponse(uniq_ptr<Foo>&& response) {
parent_.doSomething(std::move(response));
}
I need to modify this to do some stuff (fire a timer, basically) on the main thread using a function postToMainThread which takes a lambda, and then call doSomething as before. Posting to main thread with a dummy response works fine, but when I try to pass/move the lambda through, I get a segfault as something on the other side tries to take ownership of the response:
void MyClass::onResponse(uniq_ptr<Foo>&& response) {
postToMainThread([this, &response]() {
// Do some stuff that must be on main thread
parent_.doSomething(std::response);
}
}
I've seen a number of examples that use postToMainThread([this, response = std::move(response)]() {... but that does not compile due to a copy constructor on unique pointer error. I gather I need to transfer ownership of the response, but I'm not sure how.
Ok, figured it out. I added a response_ property to MyClass, and moved it in MyClass::onResponse(). That in turn fired the post and timer, which called a new MyClass::XXX(). This in turn performed parent_.doSomething(std::move(response_)) with the stored response. Whew!
So, I've advertised for DCCA application in my extension via fd_disp_register and I can parse and prepare the response message and at the end sending them from my callback function with no issue.
This always works if the answer message is prepared inside of callback function. But what if i want to reply the request message outside of my callback function ?
So, I tried it with a sample code. I changed the callback function logic so there were no sending message from it and instead another thread tries to fetch some information and send out the response.
This absolutely failed, because as soon as callback returns (with 0), the next action gonna take place (according to disp_action value) which is not in my favor.
So, I'd like to ask what is your solution to handle such case, I mean sending out the response messages outside of the callback function ?
Thanks.
I'm not sure I've ever done this before, but looking at libfdproto.h...
enum disp_action {
DISP_ACT_CONT, /* The next handler should be called, unless *msg == NULL. */
DISP_ACT_SEND, /* The updated message must be sent. No further callback is called. */
DISP_ACT_ERROR /* An error must be created and sent as a reply -- not valid for callbacks, only for fd_msg_dispatch. */
};
...it sounds like you want to set *act = DISP_ACT_CONT; and *msg = NULL; (because you've taken ownership of the message).
Does that work?
I have a test which in which I check retry mechanism for token authorisation. Inside that test I return null as token in the beginning and then I return a valid token, like this:
whenever(accountManager.getToken())
.thenReturn(null)
.thenReturn("some_token")
Then I have an Observable:
return Observable.just(accountManager.getToken())
...
.retryWhen { retryOnAuthExceptionWithBackoff(it) }
It should get the token, send it somewhere, wait for response and then it the response is wrong, retry the whole process again until it succeeds.
The problem is that when retryWhen() kicks in, the source observable is not called again, just its initial value is returned immediately.
On the other hand, this does work:
return Observable.just(null)
.map{ accountManager.getToken() }
...
.retryWhen { retryOnAuthExceptionWithBackoff(it) }
Is it by design or is it a bug? If it's by design, what would be an elegant way to write this, because Observable.just(null) looks just ugly.
The just() takes a constant value reference and keeps handing out the same reference to subscribers.
What you need is fromCallable:
Observable.fromCallable(() -> accountManager.getToken())
...
Whenever a new subscriber (such as a retry) comes in, the lambda is executed again.
I want to read elements from the database and return them as JSON objects.
Scalatra is set up to return JSON.
Databaseschema is created.
Players are added.
The following code seems to be the main problem:
get("/") {
inTransaction {
List(from(MassTournamentSchema.players)(s => select(s)))
}
}
I get the following error:
"No session is bound to current thread, a session must be created via Session.create and bound to the thread via 'work' or 'bindToCurrentThread' Usually this error occurs when a statement is executed outside of a transaction/inTrasaction block "
I want to do it right so simply adding something like "Session.create" may not really be the right way.
Can anyone help a scalatra-noob? :-)
I think that your comment is on the right track. The inTransaction block will bind a JDBC connection to a thread local variable and start the connection on it. If the select doesn't occur on the same thread, you'll see an error like the one your received. There are two things I would suggest that you try:
Start your transaction later
List(inTransaction {
from(MassTournamentSchema.players)(s => select(s))
})
I'm not familiar with Scalatra's List, but it's possible that it's accepting a by-name parameter and executing it later on a different thread.
Force an eager evaluation of the query
inTransaction {
List(from(MassTournamentSchema.players)(s => select(s)).toList)
}
Here the .toList call will turn the Query object Squeryl returns into a Scala List immediately and guard against any lazy evaluation errors caused by later iteration.
I made a class that has an asynchronous OpenWebPage() function. Once you call OpenWebPage(someUrl), a handler gets called - OnPageLoad(reply). I have been using a global variable called lastAction to take care of stuff once a page is loaded - handler checks what is the lastAction and calls an appropriate function. For example:
this->lastAction == "homepage";
this->OpenWebPage("http://www.hardwarebase.net");
void OnPageLoad(reply)
{
if(this->lastAction == "homepage")
{
this->lastAction = "login";
this->Login(); // POSTs a form and OnPageLoad gets called again
}
else if(this->lastAction == "login")
{
this->PostLogin(); // Checks did we log in properly, sets lastAction as new topic and goes to new topic URL
}
else if(this->lastAction == "new topic")
{
this->WriteTopic(); // Does some more stuff ... you get the point
}
}
Now, this is rather hard to write and keep track of when we have a large number of "actions". When I was doing stuff in Python (synchronously) it was much easier, like:
OpenWebPage("http://hardwarebase.net") // Stores the loaded page HTML in self.page
OpenWebpage("http://hardwarebase.net/login", {"user": username, "pw": password}) // POSTs a form
if(self.page == ...): // now do some more checks etc.
// do something more
Imagine now that I have a queue class which holds the actions: homepage, login, new topic. How am I supposed to execute all those actions (in proper order, one after one!) via the asynchronous callback? The first example is totally hard-coded obviously.
I hope you understand my question, because frankly I fear this is the worst question ever written :x
P.S. All this is done in Qt.
You are inviting all manner of bugs if you try and use a single member variable to maintain state for an arbitrary number of asynchronous operations, which is what you describe above. There is no way for you to determine the order that the OpenWebPage calls complete, so there's also no way to associate the value of lastAction at any given time with any specific operation.
There are a number of ways to solve this, e.g.:
Encapsulate web page loading in an immutable class that processes one page per instance
Return an object from OpenWebPage which tracks progress and stores the operation's state
Fire a signal when an operation completes and attach the operation's context to the signal
You need to add "return" statement in the end of every "if" branch: in your code, all "if" branches are executed in the first OnPageLoad call.
Generally, asynchronous state mamangment is always more complicated that synchronous. Consider replacing lastAction type with enumeration. Also, if OnPageLoad thread context is arbitrary, you need to synchronize access to global variables.