How to wait for socket.on in nodejs - javascript

I would like to know how to wait on an socket.on call. I know that one could use the callbacks as described here, but this is not applicable in my case (at least I think it is not). The following is what I have:
index.html
...
socket.on('update_img', function(data) {
// Do something
});
scanner.addListener('scan', function(content) {
socket.emit('answer', content);
});
and then on the server:
...
client.emit('update_img', some_data);
...
client.on('answer', function(data) {
// do something with the answer
});
what basically happens, I send something to the frontend which then generates an image. At the same time, the library in the browser (instascan, thus scanner.addListener) waits for reading a QR-code and sends its content back to the server. So what I now need is that client.on('answer', ...); waits for this answer.
Is there any way to achieve this?

Essentially with client.on(...) you're adding the callback to that event, meaning that whenever that "anwser" event ist emitted from the client, it will be called on the server.
So if you make sure that socket.emit("anwser") on the client, is only called after you sent the image from the server, the server just has to listen to the "anwser" event and may assume that everything happened as expected.
Therefore you dont actually have to "wait" explicitly.
EDIT: Misunderstood your flow. Will update my answer

Related

Ajax calls DURING another Ajax call to receive server's task calculation status and display it to the client as a progression bar

I'm trying to figure out if there's any chance to receive the status of completion of a task (triggered via an ajax call), via multiple (time intervalled) ajax calls.
Basically, during the execution of something that could take long, I want to populate some variable and return it's value when asked.
Server code looks like this:
function setTask($total,$current){
$this->task['total'] = $total;
$this->task['current'] = $current;
}
function setEmptyTask(){
$this->task = [];
}
function getTaskPercentage(){
return ($this->task['current'] * 100) / $this->task['total'];
}
function actionGetTask(){
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'percentage' => $this->getTaskPercentage(),
];
}
}
Let's say I'm in a for loop, and I know how many times I iterate over:
function actionExportAll(){
$size = sizeof($array);
$c = 0;
foreach($array as $a){
// do something that takes relatively long
$this->setTask($size,$c++);
}
}
While in the client side i have this:
function exportAll(){
var intervalId = setInterval(function(){
$.ajax({
url: '/get-task',
type: 'post',
success: function(data){
console.log(data);
}
});
},3000);
$.ajax({
url: '/export-all',
type: 'post',
success: function(data){
clearInterval(intervalId); // cancel setInterval
// ..
}
});
}
This looks like it could work, besides the fact that ajax calls done in the setInterval function are completed after "export-all" is done and goes in the success callback.
There's surely something that I'm missing in this logic.
Thanks
The problem is probably in sessions.
Let's take a look what is going on.
The request to /export-all is send by browser.
App on server calls session_start() that opens the session file and locks access to it.
The app begins the expensive operations.
In browser the set interval passes and browser send request to /get-task.
App on server tries to handle the /get-task request and calls session_start(). It is blocked and has to wait for /export-all request to finish.
The expensive operations of /export-all are finished and the response is send to browser.
The session file is unlocked and /get-task request can finally continue past session_start(). Meanwhile browser have recieved /export-all response and executes the success callback for it.
The /get-task request is finished and response is send to browser.
The browser recieves /get-task response and executes its success callback.
The best way to deal with it is avoid running the expensive tasks directly from requests executed by user's browser.
Your export-all action should only plan the task for execution. Then the task itself can be executed by some cron action or some worker in background. And the /get-task can check its progress and trigger the final actions when the task is finished.
You should take look at yiisoft/yii2-queue extension. This extension allows you to create jobs, enqueue them and run the jobs from queue by cron task or by running a daemon that will listen for tasks and execute them as they come.
Without trying to dive into your code, which I don't have time to do, I'll say that the essential process looks like this:
Your first AJAX call is "to schedule the unit of work ... somehow." The result of this call is to indicate success and to hand back some kind of nonce, or token, which uniquely identifies the request. This does not necessarily indicate that processing has begun, only that the request to start it has been accepted.
Your next calls request "progress," and provide the nonce given in step #1 as the means to refer to it. The immediate response is the status at this time.
Presumably, you also have some kind of call to retrieve (and remove) the completed request. The same nonce is once again used to refer to it. The immediate response is that the results are returned to you and the nonce is cancelled.
Obviously, you must have some client-side way to remember the nonce(s). "Sessions" are the most-common way to do that. "Local storage," in a suitably-recent web browser, can also be used.
Also note ... as an important clarification ... that the title to your post does not match what's happening: one AJAX call isn't happening "during" another AJAX call. All of the AJAX calls return immediately. But, all of them refer (by means of nonces) to a long-running unit of work that is being carried out by some other appropriate means.
(By the way, there are many existing "workflow managers" and "batch processing systems" out there, open-source on Github, Sourceforge, and other such places. Be sure that you're not re-inventing what someone else has already perfected! "Actum Ne Agas: Do Not Do A Thing Already Done." Take a few minutes to look around and see if there's something already out there that you can just steal.)
So basically I found the solution for this very problem by myself.
What you need to do is to replace the above server side's code into this:
function setTask($total,$current){
$_SESSION['task']['total'] = $total;
$_SESSION['task']['current'] = $current;
session_write_close();
}
function setEmptyTask(){
$_SESSION['task'] = [];
session_write_close();
}
function getTaskPercentage(){
return ($_SESSION['task']['current'] * 100) / $_SESSION['task']['total'];
}
function actionGetTask(){
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'percentage' => $this->getTaskPercentage(),
];
}
}
This works, but I'm not completely sure if is a good practice.
From what I can tell, it seems like it frees access to the $_SESSION variable and makes it readable by another session (ence my actionGetTask()) during the execution of the actionExportAll() session.
Maybe somebody could integrate this answer and tell more about it.
Thanks for the answers, I will certainly dig more in those approaches and maybe try to make this same task in a better, more elegant and logic way.

Javascript: How did I get here? (Viewing data sent by server, non-AJAX.)

I've got a React-based app that works like this: The user makes a request for "foo", the server returns basic page info (applicable to all pages on the site), and when the client receives this (DOMContentLoaded), it does an AJAX call for the internal details "foo" and renders that.
But is it possible, if I send the data on the first request, to skip the AJAX call? (I tried this previously but was very new to React, which is how I came up with the current scheme. It's come up again because now I'm handling previously saved items.) So, I'm in my DOMContentLoaded listener, and I can see (in the Browser|Network|Response area of Chrome) all the data that has been sent by the server. It's everything I need, and it's right there, but I can't find a way to access it in Javascript.
The searches I've done have almost all turned up AJAX requests. (I am using JQuery, if that helps.) Obviously I can handle loading saved data using the same gag I'm currently using, and maybe that's a an all-around better approach.
So, once again, the question is: Is it possible to look at the response from a non-AJAX place? If it is possible, is it advisable?
Update: Let me walk through an example scenario.
The user goes to "/foo".
The server response is {:some "json"}.
In the Javascript onReady, I can do this:
console.log(window.location);
and I'll see "/foo". But can I see {:some "json"}? And how? Contrast with the AJAX call version:
The user goes to "/foo".
The server response is nothing (i.e., a 200 but no body).
The Javascript onReady has:
$.ajax({
url: "/foo/data"
type: "GET",
success: function (req) {...} //req has {:some data} in it!
So, when I make an AJAX call, I get the request. Is there any way to get that {:some data} on a non-AJAX call? This doesn't work, but I could see something like:
x = window.response();
or
x = Response.last();
Neither of those things exist, of course. I hope that clarifies what I'm looking for.
You could drop a script tag on your server-rendered page that includes a global var accessible by your script bundle. e.g.,
<script>
var myGlobalVar = { ... server data ... } <!-- // note: this is rendered raw by your server
</script>
<script src="myScriptBundle.min.js"></script>
Or, alternatively you could look into server-side rendering, which is possible with React. Check out the implementation in Redux: http://redux.js.org/docs/recipes/ServerRendering.html

How to make casperJS wait until .change() event is finished?

I am triggering a change event in my casperJS script which triggers an AJAX request like such:
casper.evaluate(function(i) {
$("form:eq(2) select option:eq(" + i + ")").attr("selected", "selected").change();
},i);
How can I make casperJS wait until the underlying AJAX request has been finished? Already tried to look at the docs but I am more or less stuck. Can anyone guide me into the right direction?
You can always do this in a static way using casper.wait.
casper.thenEvaluate(function(i) {
// change()
},i).wait(5000).then(function(){
// further processing
});
And hope that the request is done in 5 seconds, but maybe you lose some time waiting when the request is done much sooner than 5 seconds. The problem is that as soon as the request is finished doesn't mean that the page is ready/changed.
Another possibility would be to wait for the request to finish, but for this to work you will need to register for the success event of the request somehow. Most of the time you don't have access to this from the global scope. If you do then you can use
casper.thenEvaluate(function(i) {
window._someUniqueVariable = false;
registerSuccessEvent(function(data){
window._someUniqueVariable = true;
});
},i).waitFor(function check(){
return this.evaluate(function(){
window._someUniqueVariable = true;
});
}, function(){
// further processing
});
A more Casper-way of doing that would be to use casper.waitForResource, but then you would need to know the url beforehand or at least able to deduce it from the page.
In the general case, when the request comes back it does something to your page. So you should be able to waitForSelector with a new element or waitForSelectorTextChange or waitUntilVisible etc.
you probably missed waitForResource
from the docs: http://casperjs.readthedocs.org/en/latest/modules/casper.html#waitforresource
casper.waitForResource("you url here", function()
{
// place your code here
});

One entry point for all ajax callbacks for a particular call in javascript

When communicating with a server in javascript in my single page browser application, I would like to provide a callback function that is always called after the server replies, regardless of whether the result was a success or some kind of error.
Two cases where I need this:
1) I want to disable a "save" button while waiting for the server's response, and enable it again after the server responds with an error or a success.
2) I have a polling mechanism where I want to prevent stacking of calls when the server for some reason is being slow to respond - I want to wait for one poll call to finish before making the next.
One solution I have right now involves making sure that two functions (success and error) get passed along as options in a long method chain, which feels like a fragile and cumbersome solution (pseudo-ish code):
function doCall() {
framework1.callit({success : myCallback, error : myCallback})
};
framework123.callit = function(options) {
options = options || {};
if (options.error) {
var oldError = options.error;
options.error = function(errorStuff) {
// callit error stuff
oldError(errorStuff);
} else {
// callit error stuff
}
generalCallFunction(options);
}
function generalCallFunction(options) {
options = // ... checking success and error once again to get general success and error stuff in there, plus adding more options
ajax( blah, blah, options);
}
I also have a backbone solution where I listen to the sync event plus an error callback, in similar ways as above.
I'm always scared that error or success functions get lost on the way, and the whole thing is hard to follow.
Any framework or pattern for making this stuff as easy as possible? Is it a weird thing to have general things that should always happen whether the result was an error or a success?
You can use jQuery.ajax({ details here... ).always(callback);
Or, in Backbone
// logic to create model here
model.fetch().always(callback);

Make Ajax Request Recursive - Checks if File Exists

Basically just looking to see if a particular txt file exists on the server, and if so, do further processing; however, I don't think my recursion is correct, so can someone offer a few pointers - here's what I have:
function fileExists(filename) {
$.ajax({
type: 'HEAD',
url: 'http://www.example.com/system/'+filename+'.txt',
success: function() {
// Further processing if file exists
},
error: function() {
// File does not exists, run through function again-
return arguments.callee(filename);
}
});
}
It's pretty basic, there's some processing before hand that actually creates the file; however the issue is it's FTP-ed up to our domain, which means timing can vary by a few seconds, so basically I just want it to recheck until it sees that the file exists. I'll modify it a little afterwards to control the stack, possibly setting a timeout of half a second or something, but I'm not that great with javascript, so I need a few pointers to make this recursive. Any help is GREATLY appreciated.
the issue is when you try to call fileExists again via arguments.callee(fileName), the scope of the error method isn't what you think it is.
Just call fileExists.
The other you are going to have is that if your server is quick, you are going to be firing a ton of requests. You probably want to wait some time between requests. So make error contain
setTimeout(function(){
console.log('trying again....'); // this won't work in IE, I *think*
fileExists(filename);
}, 1000); // try again in a second
Finally, you should realize that the error callback only gets invoked if the server returns a 500. The 500 code usually means there was an error on your server. If a file doesn't exist, you should probably return json to indicate the file doesn't exist, and handle that case in your success callback.
error: function() {
fileExists(filename);
}

Categories

Resources