Multiple ajax request parallel issue - ajax

I am trying to make 100 ajax request in $.when at a time on Chrome :
var task = [];
List.forEach(function (item, index) { // List length is 100
tasks.push(ajaxUploadTrackable(item));
}
$.when.apply(null, tasks).then(function (result) {
// do somthing
}
but some request got failed.
please give me any idea.
is there pending time limitation or maximum number of requests at a time???

Insted of loop check for sync and async
Put your AJAX call in a function and call it from the AJAX callback:
check Link

Related

Sails.js sails.io.js, blueprints not getting events from .publish(), how to subscribe to all events?

I don't know why I'm not getting notification events from sails models from model.publish().
In pre-1.x sailsjs, similar client-side code had worked and I would get every event when records are created, updated or deleted. So, I must be misunderstanding something.
How do I subscribe to all events for any records from CRUD operations?
On the server side, I have Job.js and JobController.js.
In Job.js model, this test just creates a new record every 10 secs:
test: async function(dataset) {
let count = 0;
setInterval(async function() {
count++;
let newjob = {
dataset: dataset,
state: 'delayed',
name: "job name "+count
};
let job = await Job.create(newjob).fetch()
sails.log.info('created test job: ',JSON.stringify(job));
Job.publish([job.id],job);
},10000);
}
In JobController.js, called by the client and starts the test rolling:
submittest: async function(req,res) {
let dataset = await Dataset.Get({});
await Job.test(dataset[0].id);
return res.ok({status:'ok'});
}
In the client test.html, io.socket.get operations are successful, but I never see an event:
...
<script>
io.socket.get('/job', function(body, JWR) {
console.log('and with status code: ', JWR.statusCode);
setTimeout(function() {
io.socket.get('/job/submittest', function (body,JWR) {
io.socket.on('job', function(msg) {
console.log("job event",msg); // not getting here. why?
});
});
},2000)
});
</script>
This all runs fine but the problem is, no events are seen from the client side. Why? Am I not subscribed to events with the initial io.socket.get('/job')?
Essentially, what is happening here, is you are shouting into an empty box about a new record in your model, but no one is listening to you in that empty box.
In other words, you need to subscribe the socket connection to the model updates.
See: https://sailsjs.com/documentation/reference/web-sockets/resourceful-pub-sub/subscribe
Also, checkout the answer to this question for a quick how to.

Should I create a .factory in order to share a variable's value to two ajax requests?

Using angularjs I have made two ajax json requests, the first request is retrieving channel's online / offline status and the second ajax json request is for the channel's info (logo, name, status etc).
I assigned the variable signal to 'data.stream' which is the online / offline status for channels to share signal between json requests. In Google Developer console I am receiving a value of null. I did some research here http://www.ng-newsletter.com/posts/beginner2expert-services.html and found that using a service might be a solution. I followed the directions but I'm still unable to get the scope between json request to recognize signal.
I read that rootscope could be used but it's not recommend, not sure how true that is because a novice using angular but I want start my angular journey by applying best practices.
Recap: Using Angular Ajax to make a jsonp request to twitch api, I am make two requests one to retrieve the online / offline status of channels in my streamers array, and the other ajax json request is to retrieve the channel's info, and I need the scope of the variable signal which has been assigned the value data.stream to be seen between ajax jsonp requests. Please let me know if this is a logical approach or if I'm "going around the world again".
Here is a plunker: plnkr.co/edit/6sb39NktX7CwfnQFxNNX
// creating a service for signal ?
app.factory('signal', function() {
var signal = {};
return signal;
})
// declaring my TwitchController and dependencies
app.controller('TwitchController', ['$scope', '$http', 'signal', function($scope, $http, signal) {
// streamers array with array of channels
var streamers = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff", "medrybw"];
$scope.imgs;
$scope.signal = signal;
var self = this;
//empty array
self.info = [];
for (var i = 0; i < streamers.length; i++) {
var url = "https://api.twitch.tv/kraken/channels/";
var streamUrl = "https://api.twitch.tv/kraken/streams/";
var callback = "/?callback=JSON_CALLBACK";
//json ajax request for channels online and offline status
$http.jsonp(streamUrl + streamers[i] + callback).success(function(data) {
//provides status of shows online and offline
signal = data.stream;
console.log(signal)
});
// json ajax request for channels and channel's info
$http.jsonp(url + streamers[i] + callback).success(function(data) {
// if channel does not have a logo image, this jpg will be the placeholder
// if statement test channel status (online or offline)
if (!signal) {
signal = "offline";
} else if (signal) {
signal = 'online';
}
// pushing retreive data from twitch.tv into array self.info
self.info.push(data);
});
Your issue here is async call to $http. You need to use $http.then and chain the promises. You do not need a factory for this instance but it is best practice to have one that just returns your info object. I didn't know exactly the format you wanted so I created one. Here is the plunker: http://plnkr.co/edit/ecwk0vGMJCvkqCbZa7Cw?p=preview
var app = angular.module('Twitch', []);
// declaring my TwitchController and dependencies
app.controller('TwitchController', ['$scope', '$http', function($scope, $http) {
// streamers array with array of channels
var streamers = ['freecodecamp', 'storbeck','terakilobyte', 'habathcx', 'RobotCaleb', 'thomasballinger', 'noobs2ninjas', 'beohoff', 'medrybw' ];
//empty array
$scope.info = [];
var url = 'https://api.twitch.tv/kraken/channels/';
var streamUrl = 'https://api.twitch.tv/kraken/streams/';
var callback = '/?callback=JSON_CALLBACK';
angular.forEach(streamers, function(stream) {
//json ajax request for channels online and offline status
$http.jsonp(streamUrl + stream + callback).then(function (data) {
//provides status of shows online and offline
// json ajax request for channels and channel's info
$http.jsonp(url + stream + callback).then(function (channelData) {
// pushing retrieve data from twitch.tv into array self.info
$scope.info.push(
{
url: url + stream,
stream: stream,
status: !data.stream ? 'offline' : 'online', // ternary statement test channel status (online or offline)
logo: channelData.data.logo ? channelData.data.logo : 'placeholderlogo.jpg' // if channel does not have a logo image, this jpg will be the placeholder
}
);
});
});
});
}]);

Angular $http returning new values only once

I am new to Angular, and set up a simple example with a REST Api config in Codeigniter that returns a json (default) thread list. No problems!
Until, I add an update to the Database. If I clear/then call getThreads again, I receive the same list of items. A page refresh solves this. I can see in firebug that its only calling the url:api/example/threadlist/id/'x' once per page load.
function ThreadsCtrl($scope, $http, $templateCache) {
$scope.getThreads = function(id) {
if (!id) { id = 'reset'; }
$http({method: 'GET', url: 'api/example/threadlist/id/' + id, cache: $templateCache}).
success(function(data) {
$scope.threadslist = data; //set view model
}).
error(function(data) {
$scope.threadslist = data || "Request failed";
});
};
How would I make it so that it always calls a new list of data rather than reuses the old.
Thanks!
If i understood your question correctly your ajax call is being cached so you have to remove cache:$templatecache from your code

can't seem to get progress events from node-formidable to send to the correct client over socket.io

So I'm building a multipart form uploader over ajax on node.js, and sending progress events back to the client over socket.io to show the status of their upload. Everything works just fine until I have multiple clients trying to upload at the same time. Originally what would happen is while one upload is going, when a second one starts up it begins receiving progress events from both of the forms being parsed. The original form does not get affected and it only receives progress updates for itself. I tried creating a new formidable form object and storing it in an array along with the socket's session id to try to fix this, but now the first form stops receiving events while the second form gets processed. Here is my server code:
var http = require('http'),
formidable = require('formidable'),
fs = require('fs'),
io = require('socket.io'),
mime = require('mime'),
forms = {};
var server = http.createServer(function (req, res) {
if (req.url.split("?")[0] == "/upload") {
console.log("hit upload");
if (req.method.toLowerCase() === 'post') {
socket_id = req.url.split("sid=")[1];
forms[socket_id] = new formidable.IncomingForm();
form = forms[socket_id];
form.addListener('progress', function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
});
form.parse(req, function (err, fields, files) {
file_name = escape(files.upload.name);
fs.writeFile(file_name, files.upload, 'utf8', function (err) {
if (err) throw err;
console.log(file_name);
})
});
}
}
});
var socket = io.listen(server);
server.listen(8000);
If anyone could be any help on this I would greatly appreciate it. I've been banging my head against my desk for a few days trying to figure this one out, and would really just like to get this solved so that I can move on. Thank you so much in advance!
Can you try putting console.log(socket_id);
after form = forms[socket_id]; and
after progress = (bytesReceived / bytesExpected * 100).toFixed(0);, please?
I get the feeling that you might have to wrap that socket_id in a closure, like this:
form.addListener(
'progress',
(function(socket_id) {
return function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
};
})(socket_id)
);
The problem is that you aren't declaring socket_id and form with var, so they're actually global.socket_id and global.form rather than local variables of your request handler. Consequently, separate requests step over each other since the callbacks are referring to the globals rather than being proper closures.
rdrey's solution works because it bypasses that problem (though only for socket_id; if you were to change the code in such a way that one of the callbacks referenced form you'd get in trouble). Normally you only need to use his technique if the variable in question is something that changes in the course of executing the outer function (e.g. if you're creating closures within a loop).

How can I pass parameters with callback functions to search APIs like Yahoo BOSS and BING?

I am using Yahoo BOSS and Bing APIs to provide search functionality to my site. Specificaly, I use their JSON response formats where I would pass a callback function to the search provider that would later be called back with the search results. My callback function actually gets called, but the problem is, if I make more than one requests at a time, I can't tell which request a certain response is for. To this end, is there a way to pass additional parameters with the callback function to the search provider so that I can later use it to identify which response goes with which request?
Thank you
I have a same problem with you! I googled and find some solutions
and I has solve my problem. Now i show it to you, I hope it can help you :)
Previous code:
function MakeGeocodeRequest(credentials) {
var pins = checkLocation.d
$.each(pins, function (index, pin) {
var geocodeRequest = 'http://ecn.dev.virtualearth.net/REST/v1/Locations/' + pin.City + ',' + pin.Country + '?output=json&jsonp=GeocodeCallback&key=' + credentials;
CallRestService(geocodeRequest);
});
function CallRestService(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
function GeocodeCallback(result) {.. to do with result callback, --> i want to add some pin infomation here}
Because each sccipt when add to document ( document.body.appendChild(script);) it will be run --> and callback, you cant add more params.
I solve it by request through ajax (doesnt add to document any more), when the ajax call success --> I call the GeocodeCallback(result, pin)
Here is the complete code.
function MakeGeocodeRequest(credentials) {
var pins = checkLocation.d;
$.each(pins, function (index, pin) {
$.ajax({
url:"http://ecn.dev.virtualearth.net/REST/v1/Locations/",
dataType: "jsonp",
data:{key:credentials,q:pin.City + ',' + pin.Country},
jsonp:"jsonp",
success: function(result){
GeocodeCallback(result,pin);
}
});
});
}
function GeocodeCallback(result,pin) { ... to do here}

Resources